diff --git a/Dockerfile b/Dockerfile index 50e1c79..ba58e95 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,81 @@ -FROM python:3.5-slim -MAINTAINER Jiajie Zhang +FROM ubuntu:16.04 + +ENV DEBIAN_FRONTEND noninteractive + +RUN apt-get update -y +RUN apt-get install -y --no-install-recommends \ + apt-transport-https \ + build-essential \ + git \ + libcurl4-openssl-dev \ + libxml2-dev \ + software-properties-common \ + libreadline-dev \ + libpcre++-dev \ + libblas-dev \ + liblapack-dev \ + libatlas-base-dev \ + gfortran \ + liblzma-dev \ + libbz2-dev \ + locales \ + zlib1g-dev \ + xserver-xorg \ + xdm \ + xfonts-base \ + xfonts-100dpi \ + xfonts-75dpi + +# Locales +RUN locale-gen en_GB.UTF-8 +ENV LANG en_GB.UTF-8 +ENV LANGUAGE en_GB:en +ENV LC_ALL en_GB.UTF-8 + +# Python 3.6 +RUN add-apt-repository -y ppa:deadsnakes/ppa && \ + apt remove -y python3-apt && \ + apt-get update && \ + apt-get install -y --no-install-recommends \ + python3.6 python3.6-dev python3-pip python3-apt python3-tk \ + python3-setuptools \ + software-properties-common python3-software-properties && \ + rm /usr/bin/python3 && \ + ln -s /usr/bin/python3.6 /usr/bin/python3 && \ + cp /usr/lib/python3/dist-packages/apt_pkg.cpython-35m-x86_64-linux-gnu.so \ + /usr/lib/python3/dist-packages/apt_pkg.so + +RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.6 1 +RUN update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1 + +# R 3.3 +#RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9 && \ +# add-apt-repository 'deb [arch=amd64,i386] https://cran.rstudio.com/bin/linux/ubuntu xenial/' && \ +# apt-get update && \ +# apt-get install -y --no-install-recommends \ +# r-recommended=3.3.3-1xenial0 r-base=3.3.3-1xenial0 + +#RUN R -e "install.packages(c('robustbase', 'rrcov'), repos='http://cran.us.r-project.org')" + +#RUN R -e "source('http://bioconductor.org/biocLite.R'); \ +# biocLite(''); \ +# biocLite('GEOquery'); \ +# biocLite('data.table'); \ +# biocLite('rhdf5'); \ +# biocLite('limma'); \ +# biocLite('oligo'); \ +# biocLite('ArrayExpress'); \ +# biocLite('magrittr'); \ +# biocLite('dplyr'); \ +# biocLite('AnnotationDbi'); \ +# biocLite('WGCNA');" + +# RUN R -e "install.packages(c('INSPIRE', 'MASS', 'lme4', 'lmerTest'), repos='http://cran.us.r-project.org')" -COPY . /app RUN pip3 install --upgrade pip -RUN pip3 install --no-cache-dir -r /app/requirements.txt +RUN pip3 install wheel +RUN pip3 install numpy scipy docutils six pytest matplotlib lxml PyQt5 ete3 +COPY . /app WORKDIR /app RUN python3 setup.py install diff --git a/ete2/__init__.py b/ete2/__init__.py deleted file mode 100644 index c491358..0000000 --- a/ete2/__init__.py +++ /dev/null @@ -1,82 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - - -# Note that the use of "from x import *" is safe here. Modules include -# the __all__ variable. - -from sys import stderr -from coretype.tree import * -from coretype.seqgroup import * -from phylo.phylotree import * -from evol.evoltree import * -from webplugin.webapp import * -from phyloxml import Phyloxml, PhyloxmlTree -from nexml import Nexml, NexmlTree -from evol import EvolTree - -try: - from coretype.arraytable import * -except ImportError, e: - print >>stderr, "Clustering module could not be loaded" - print e -else: - from clustering.clustertree import * - -try: - from phylomedb.phylomeDB3 import * -except ImportError, e: - print >>stderr, " MySQLdb module could not be loaded" - print e - -try: - from treeview.main import * - from treeview.faces import * - from treeview import faces - from treeview import layouts - from treeview.svg_colors import * -except ImportError, e: - print >>stderr, "Treeview module could not be loaded" - print e - -# Do not modify the following line. It will be checked during -# installation -__ETEID__="09fb3d1678500696ca3cd65158f18c59" diff --git a/ete2/__init__.pyc b/ete2/__init__.pyc deleted file mode 100644 index 4595c10..0000000 Binary files a/ete2/__init__.pyc and /dev/null differ diff --git a/ete2/_argparse.py b/ete2/_argparse.py deleted file mode 100644 index ebb0381..0000000 --- a/ete2/_argparse.py +++ /dev/null @@ -1,2402 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -# Author: Steven J. Bethard . - -"""Command-line parsing library - -This module is an optparse-inspired command-line parsing library that: - - - handles both optional and positional arguments - - produces highly informative usage messages - - supports parsers that dispatch to sub-parsers - -The following is a simple usage example that sums integers from the -command-line and writes the result to a file:: - - parser = argparse.ArgumentParser( - description='sum the integers at the command line') - parser.add_argument( - 'integers', metavar='int', nargs='+', type=int, - help='an integer to be summed') - parser.add_argument( - '--log', default=sys.stdout, type=argparse.FileType('w'), - help='the file where the sum should be written') - args = parser.parse_args() - args.log.write('%s' % sum(args.integers)) - args.log.close() - -The module contains the following public classes: - - - ArgumentParser -- The main entry point for command-line parsing. As the - example above shows, the add_argument() method is used to populate - the parser with actions for optional and positional arguments. Then - the parse_args() method is invoked to convert the args at the - command-line into an object with attributes. - - - ArgumentError -- The exception raised by ArgumentParser objects when - there are errors with the parser's actions. Errors raised while - parsing the command-line are caught by ArgumentParser and emitted - as command-line messages. - - - FileType -- A factory for defining types of files to be created. As the - example above shows, instances of FileType are typically passed as - the type= argument of add_argument() calls. - - - Action -- The base class for parser actions. Typically actions are - selected by passing strings like 'store_true' or 'append_const' to - the action= argument of add_argument(). However, for greater - customization of ArgumentParser actions, subclasses of Action may - be defined and passed as the action= argument. - - - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, - ArgumentDefaultsHelpFormatter -- Formatter classes which - may be passed as the formatter_class= argument to the - ArgumentParser constructor. HelpFormatter is the default, - RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser - not to change the formatting for help text, and - ArgumentDefaultsHelpFormatter adds information about argument defaults - to the help. - -All other classes in this module are considered implementation details. -(Also note that HelpFormatter and RawDescriptionHelpFormatter are only -considered public as object names -- the API of the formatter objects is -still considered an implementation detail.) -""" - -__version__ = '1.2.1' -__all__ = [ - 'ArgumentParser', - 'ArgumentError', - 'ArgumentTypeError', - 'FileType', - 'HelpFormatter', - 'ArgumentDefaultsHelpFormatter', - 'RawDescriptionHelpFormatter', - 'RawTextHelpFormatter', - 'Namespace', - 'Action', - 'ONE_OR_MORE', - 'OPTIONAL', - 'PARSER', - 'REMAINDER', - 'SUPPRESS', - 'ZERO_OR_MORE', -] - - -import copy as _copy -import os as _os -import re as _re -import sys as _sys -import textwrap as _textwrap - -from gettext import gettext as _ - -try: - set -except NameError: - # for python < 2.4 compatibility (sets module is there since 2.3): - from sets import Set as set - -try: - basestring -except NameError: - basestring = str - -try: - sorted -except NameError: - # for python < 2.4 compatibility: - def sorted(iterable, reverse=False): - result = list(iterable) - result.sort() - if reverse: - result.reverse() - return result - - -def _callable(obj): - return hasattr(obj, '__call__') or hasattr(obj, '__bases__') - - -SUPPRESS = '==SUPPRESS==' - -OPTIONAL = '?' -ZERO_OR_MORE = '*' -ONE_OR_MORE = '+' -PARSER = 'A...' -REMAINDER = '...' -_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' - -# ============================= -# Utility functions and classes -# ============================= - -class _AttributeHolder(object): - """Abstract base class that provides __repr__. - - The __repr__ method returns a string in the format:: - ClassName(attr=name, attr=name, ...) - The attributes are determined either by a class-level attribute, - '_kwarg_names', or by inspecting the instance __dict__. - """ - - def __repr__(self): - type_name = type(self).__name__ - arg_strings = [] - for arg in self._get_args(): - arg_strings.append(repr(arg)) - for name, value in self._get_kwargs(): - arg_strings.append('%s=%r' % (name, value)) - return '%s(%s)' % (type_name, ', '.join(arg_strings)) - - def _get_kwargs(self): - return sorted(self.__dict__.items()) - - def _get_args(self): - return [] - - -def _ensure_value(namespace, name, value): - if getattr(namespace, name, None) is None: - setattr(namespace, name, value) - return getattr(namespace, name) - - -# =============== -# Formatting Help -# =============== - -class HelpFormatter(object): - """Formatter for generating usage messages and argument help strings. - - Only the name of this class is considered a public API. All the methods - provided by the class are considered an implementation detail. - """ - - def __init__(self, - prog, - indent_increment=2, - max_help_position=24, - width=None): - - # default setting for width - if width is None: - try: - width = int(_os.environ['COLUMNS']) - except (KeyError, ValueError): - width = 80 - width -= 2 - - self._prog = prog - self._indent_increment = indent_increment - self._max_help_position = max_help_position - self._width = width - - self._current_indent = 0 - self._level = 0 - self._action_max_length = 0 - - self._root_section = self._Section(self, None) - self._current_section = self._root_section - - self._whitespace_matcher = _re.compile(r'\s+') - self._long_break_matcher = _re.compile(r'\n\n\n+') - - # =============================== - # Section and indentation methods - # =============================== - def _indent(self): - self._current_indent += self._indent_increment - self._level += 1 - - def _dedent(self): - self._current_indent -= self._indent_increment - assert self._current_indent >= 0, 'Indent decreased below 0.' - self._level -= 1 - - class _Section(object): - - def __init__(self, formatter, parent, heading=None): - self.formatter = formatter - self.parent = parent - self.heading = heading - self.items = [] - - def format_help(self): - # format the indented section - if self.parent is not None: - self.formatter._indent() - join = self.formatter._join_parts - for func, args in self.items: - func(*args) - item_help = join([func(*args) for func, args in self.items]) - if self.parent is not None: - self.formatter._dedent() - - # return nothing if the section was empty - if not item_help: - return '' - - # add the heading if the section was non-empty - if self.heading is not SUPPRESS and self.heading is not None: - current_indent = self.formatter._current_indent - heading = '%*s%s:\n' % (current_indent, '', self.heading) - else: - heading = '' - - # join the section-initial newline, the heading and the help - return join(['\n', heading, item_help, '\n']) - - def _add_item(self, func, args): - self._current_section.items.append((func, args)) - - # ======================== - # Message building methods - # ======================== - def start_section(self, heading): - self._indent() - section = self._Section(self, self._current_section, heading) - self._add_item(section.format_help, []) - self._current_section = section - - def end_section(self): - self._current_section = self._current_section.parent - self._dedent() - - def add_text(self, text): - if text is not SUPPRESS and text is not None: - self._add_item(self._format_text, [text]) - - def add_usage(self, usage, actions, groups, prefix=None): - if usage is not SUPPRESS: - args = usage, actions, groups, prefix - self._add_item(self._format_usage, args) - - def add_argument(self, action): - if action.help is not SUPPRESS: - - # find all invocations - get_invocation = self._format_action_invocation - invocations = [get_invocation(action)] - for subaction in self._iter_indented_subactions(action): - invocations.append(get_invocation(subaction)) - - # update the maximum item length - invocation_length = max([len(s) for s in invocations]) - action_length = invocation_length + self._current_indent - self._action_max_length = max(self._action_max_length, - action_length) - - # add the item to the list - self._add_item(self._format_action, [action]) - - def add_arguments(self, actions): - for action in actions: - self.add_argument(action) - - # ======================= - # Help-formatting methods - # ======================= - def format_help(self): - help = self._root_section.format_help() - if help: - help = self._long_break_matcher.sub('\n\n', help) - help = help.strip('\n') + '\n' - return help - - def _join_parts(self, part_strings): - return ''.join([part - for part in part_strings - if part and part is not SUPPRESS]) - - def _format_usage(self, usage, actions, groups, prefix): - if prefix is None: - prefix = _('usage: ') - - # if usage is specified, use that - if usage is not None: - usage = usage % dict(prog=self._prog) - - # if no optionals or positionals are available, usage is just prog - elif usage is None and not actions: - usage = '%(prog)s' % dict(prog=self._prog) - - # if optionals and positionals are available, calculate usage - elif usage is None: - prog = '%(prog)s' % dict(prog=self._prog) - - # split optionals from positionals - optionals = [] - positionals = [] - for action in actions: - if action.option_strings: - optionals.append(action) - else: - positionals.append(action) - - # build full usage string - format = self._format_actions_usage - action_usage = format(optionals + positionals, groups) - usage = ' '.join([s for s in [prog, action_usage] if s]) - - # wrap the usage parts if it's too long - text_width = self._width - self._current_indent - if len(prefix) + len(usage) > text_width: - - # break usage into wrappable parts - part_regexp = r'\(.*?\)+|\[.*?\]+|\S+' - opt_usage = format(optionals, groups) - pos_usage = format(positionals, groups) - opt_parts = _re.findall(part_regexp, opt_usage) - pos_parts = _re.findall(part_regexp, pos_usage) - assert ' '.join(opt_parts) == opt_usage - assert ' '.join(pos_parts) == pos_usage - - # helper for wrapping lines - def get_lines(parts, indent, prefix=None): - lines = [] - line = [] - if prefix is not None: - line_len = len(prefix) - 1 - else: - line_len = len(indent) - 1 - for part in parts: - if line_len + 1 + len(part) > text_width: - lines.append(indent + ' '.join(line)) - line = [] - line_len = len(indent) - 1 - line.append(part) - line_len += len(part) + 1 - if line: - lines.append(indent + ' '.join(line)) - if prefix is not None: - lines[0] = lines[0][len(indent):] - return lines - - # if prog is short, follow it with optionals or positionals - if len(prefix) + len(prog) <= 0.75 * text_width: - indent = ' ' * (len(prefix) + len(prog) + 1) - if opt_parts: - lines = get_lines([prog] + opt_parts, indent, prefix) - lines.extend(get_lines(pos_parts, indent)) - elif pos_parts: - lines = get_lines([prog] + pos_parts, indent, prefix) - else: - lines = [prog] - - # if prog is long, put it on its own line - else: - indent = ' ' * len(prefix) - parts = opt_parts + pos_parts - lines = get_lines(parts, indent) - if len(lines) > 1: - lines = [] - lines.extend(get_lines(opt_parts, indent)) - lines.extend(get_lines(pos_parts, indent)) - lines = [prog] + lines - - # join lines into usage - usage = '\n'.join(lines) - - # prefix with 'usage:' - return '%s%s\n\n' % (prefix, usage) - - def _format_actions_usage(self, actions, groups): - # find group indices and identify actions in groups - group_actions = set() - inserts = {} - for group in groups: - try: - start = actions.index(group._group_actions[0]) - except ValueError: - continue - else: - end = start + len(group._group_actions) - if actions[start:end] == group._group_actions: - for action in group._group_actions: - group_actions.add(action) - if not group.required: - if start in inserts: - inserts[start] += ' [' - else: - inserts[start] = '[' - inserts[end] = ']' - else: - if start in inserts: - inserts[start] += ' (' - else: - inserts[start] = '(' - inserts[end] = ')' - for i in range(start + 1, end): - inserts[i] = '|' - - # collect all actions format strings - parts = [] - for i, action in enumerate(actions): - - # suppressed arguments are marked with None - # remove | separators for suppressed arguments - if action.help is SUPPRESS: - parts.append(None) - if inserts.get(i) == '|': - inserts.pop(i) - elif inserts.get(i + 1) == '|': - inserts.pop(i + 1) - - # produce all arg strings - elif not action.option_strings: - part = self._format_args(action, action.dest) - - # if it's in a group, strip the outer [] - if action in group_actions: - if part[0] == '[' and part[-1] == ']': - part = part[1:-1] - - # add the action string to the list - parts.append(part) - - # produce the first way to invoke the option in brackets - else: - option_string = action.option_strings[0] - - # if the Optional doesn't take a value, format is: - # -s or --long - if action.nargs == 0: - part = '%s' % option_string - - # if the Optional takes a value, format is: - # -s ARGS or --long ARGS - else: - default = action.dest.upper() - args_string = self._format_args(action, default) - part = '%s %s' % (option_string, args_string) - - # make it look optional if it's not required or in a group - if not action.required and action not in group_actions: - part = '[%s]' % part - - # add the action string to the list - parts.append(part) - - # insert things at the necessary indices - for i in sorted(inserts, reverse=True): - parts[i:i] = [inserts[i]] - - # join all the action items with spaces - text = ' '.join([item for item in parts if item is not None]) - - # clean up separators for mutually exclusive groups - open = r'[\[(]' - close = r'[\])]' - text = _re.sub(r'(%s) ' % open, r'\1', text) - text = _re.sub(r' (%s)' % close, r'\1', text) - text = _re.sub(r'%s *%s' % (open, close), r'', text) - text = _re.sub(r'\(([^|]*)\)', r'\1', text) - text = text.strip() - - # return the text - return text - - def _format_text(self, text): - if '%(prog)' in text: - text = text % dict(prog=self._prog) - text_width = self._width - self._current_indent - indent = ' ' * self._current_indent - return self._fill_text(text, text_width, indent) + '\n\n' - - def _format_action(self, action): - # determine the required width and the entry label - help_position = min(self._action_max_length + 2, - self._max_help_position) - help_width = self._width - help_position - action_width = help_position - self._current_indent - 2 - action_header = self._format_action_invocation(action) - - # ho nelp; start on same line and add a final newline - if not action.help: - tup = self._current_indent, '', action_header - action_header = '%*s%s\n' % tup - - # short action name; start on the same line and pad two spaces - elif len(action_header) <= action_width: - tup = self._current_indent, '', action_width, action_header - action_header = '%*s%-*s ' % tup - indent_first = 0 - - # long action name; start on the next line - else: - tup = self._current_indent, '', action_header - action_header = '%*s%s\n' % tup - indent_first = help_position - - # collect the pieces of the action help - parts = [action_header] - - # if there was help for the action, add lines of help text - if action.help: - help_text = self._expand_help(action) - help_lines = self._split_lines(help_text, help_width) - parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) - for line in help_lines[1:]: - parts.append('%*s%s\n' % (help_position, '', line)) - - # or add a newline if the description doesn't end with one - elif not action_header.endswith('\n'): - parts.append('\n') - - # if there are any sub-actions, add their help as well - for subaction in self._iter_indented_subactions(action): - parts.append(self._format_action(subaction)) - - # return a single string - return self._join_parts(parts) - - def _format_action_invocation(self, action): - if not action.option_strings: - metavar, = self._metavar_formatter(action, action.dest)(1) - return metavar - - else: - parts = [] - - # if the Optional doesn't take a value, format is: - # -s, --long - if action.nargs == 0: - parts.extend(action.option_strings) - - # if the Optional takes a value, format is: - # -s ARGS, --long ARGS - else: - default = action.dest.upper() - args_string = self._format_args(action, default) - for option_string in action.option_strings: - parts.append('%s %s' % (option_string, args_string)) - - return ', '.join(parts) - - def _metavar_formatter(self, action, default_metavar): - if action.metavar is not None: - result = action.metavar - elif action.choices is not None: - choice_strs = [str(choice) for choice in action.choices] - result = '{%s}' % ','.join(choice_strs) - else: - result = default_metavar - - def format(tuple_size): - if isinstance(result, tuple): - return result - else: - return (result, ) * tuple_size - return format - - def _format_args(self, action, default_metavar): - get_metavar = self._metavar_formatter(action, default_metavar) - if action.nargs is None: - result = '%s' % get_metavar(1) - elif action.nargs == OPTIONAL: - result = '[%s]' % get_metavar(1) - elif action.nargs == ZERO_OR_MORE: - result = '[%s [%s ...]]' % get_metavar(2) - elif action.nargs == ONE_OR_MORE: - result = '%s [%s ...]' % get_metavar(2) - elif action.nargs == REMAINDER: - result = '...' - elif action.nargs == PARSER: - result = '%s ...' % get_metavar(1) - else: - formats = ['%s' for _ in range(action.nargs)] - result = ' '.join(formats) % get_metavar(action.nargs) - return result - - def _expand_help(self, action): - params = dict(vars(action), prog=self._prog) - for name in list(params): - if params[name] is SUPPRESS: - del params[name] - for name in list(params): - if hasattr(params[name], '__name__'): - params[name] = params[name].__name__ - if params.get('choices') is not None: - choices_str = ', '.join([str(c) for c in params['choices']]) - params['choices'] = choices_str - return self._get_help_string(action) % params - - def _iter_indented_subactions(self, action): - try: - get_subactions = action._get_subactions - except AttributeError: - pass - else: - self._indent() - for subaction in get_subactions(): - yield subaction - self._dedent() - - def _split_lines(self, text, width): - text = self._whitespace_matcher.sub(' ', text).strip() - return _textwrap.wrap(text, width) - - def _fill_text(self, text, width, indent): - text = self._whitespace_matcher.sub(' ', text).strip() - return _textwrap.fill(text, width, initial_indent=indent, - subsequent_indent=indent) - - def _get_help_string(self, action): - return action.help - - -class RawDescriptionHelpFormatter(HelpFormatter): - """Help message formatter which retains any formatting in descriptions. - - Only the name of this class is considered a public API. All the methods - provided by the class are considered an implementation detail. - """ - - def _fill_text(self, text, width, indent): - return ''.join([indent + line for line in text.splitlines(True)]) - - -class RawTextHelpFormatter(RawDescriptionHelpFormatter): - """Help message formatter which retains formatting of all help text. - - Only the name of this class is considered a public API. All the methods - provided by the class are considered an implementation detail. - """ - - def _split_lines(self, text, width): - return text.splitlines() - - -class ArgumentDefaultsHelpFormatter(HelpFormatter): - """Help message formatter which adds default values to argument help. - - Only the name of this class is considered a public API. All the methods - provided by the class are considered an implementation detail. - """ - - def _get_help_string(self, action): - help = action.help - if '%(default)' not in action.help: - if action.default is not SUPPRESS: - defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] - if action.option_strings or action.nargs in defaulting_nargs: - help += ' (default: %(default)s)' - return help - - -# ===================== -# Options and Arguments -# ===================== - -def _get_action_name(argument): - if argument is None: - return None - elif argument.option_strings: - return '/'.join(argument.option_strings) - elif argument.metavar not in (None, SUPPRESS): - return argument.metavar - elif argument.dest not in (None, SUPPRESS): - return argument.dest - else: - return None - - -class ArgumentError(Exception): - """An error from creating or using an argument (optional or positional). - - The string value of this exception is the message, augmented with - information about the argument that caused it. - """ - - def __init__(self, argument, message): - self.argument_name = _get_action_name(argument) - self.message = message - - def __str__(self): - if self.argument_name is None: - format = '%(message)s' - else: - format = 'argument %(argument_name)s: %(message)s' - return format % dict(message=self.message, - argument_name=self.argument_name) - - -class ArgumentTypeError(Exception): - """An error from trying to convert a command line string to a type.""" - pass - - -# ============== -# Action classes -# ============== - -class Action(_AttributeHolder): - """Information about how to convert command line strings to Python objects. - - Action objects are used by an ArgumentParser to represent the information - needed to parse a single argument from one or more strings from the - command line. The keyword arguments to the Action constructor are also - all attributes of Action instances. - - Keyword Arguments: - - - option_strings -- A list of command-line option strings which - should be associated with this action. - - - dest -- The name of the attribute to hold the created object(s) - - - nargs -- The number of command-line arguments that should be - consumed. By default, one argument will be consumed and a single - value will be produced. Other values include: - - N (an integer) consumes N arguments (and produces a list) - - '?' consumes zero or one arguments - - '*' consumes zero or more arguments (and produces a list) - - '+' consumes one or more arguments (and produces a list) - Note that the difference between the default and nargs=1 is that - with the default, a single value will be produced, while with - nargs=1, a list containing a single value will be produced. - - - const -- The value to be produced if the option is specified and the - option uses an action that takes no values. - - - default -- The value to be produced if the option is not specified. - - - type -- The type which the command-line arguments should be converted - to, should be one of 'string', 'int', 'float', 'complex' or a - callable object that accepts a single string argument. If None, - 'string' is assumed. - - - choices -- A container of values that should be allowed. If not None, - after a command-line argument has been converted to the appropriate - type, an exception will be raised if it is not a member of this - collection. - - - required -- True if the action must always be specified at the - command line. This is only meaningful for optional command-line - arguments. - - - help -- The help string describing the argument. - - - metavar -- The name to be used for the option's argument with the - help string. If None, the 'dest' value will be used as the name. - """ - - def __init__(self, - option_strings, - dest, - nargs=None, - const=None, - default=None, - type=None, - choices=None, - required=False, - help=None, - metavar=None): - self.option_strings = option_strings - self.dest = dest - self.nargs = nargs - self.const = const - self.default = default - self.type = type - self.choices = choices - self.required = required - self.help = help - self.metavar = metavar - - def _get_kwargs(self): - names = [ - 'option_strings', - 'dest', - 'nargs', - 'const', - 'default', - 'type', - 'choices', - 'help', - 'metavar', - ] - return [(name, getattr(self, name)) for name in names] - - def __call__(self, parser, namespace, values, option_string=None): - raise NotImplementedError(_('.__call__() not defined')) - - -class _StoreAction(Action): - - def __init__(self, - option_strings, - dest, - nargs=None, - const=None, - default=None, - type=None, - choices=None, - required=False, - help=None, - metavar=None): - if nargs == 0: - raise ValueError('nargs for store actions must be > 0; if you ' - 'have nothing to store, actions such as store ' - 'true or store const may be more appropriate') - if const is not None and nargs != OPTIONAL: - raise ValueError('nargs must be %r to supply const' % OPTIONAL) - super(_StoreAction, self).__init__( - option_strings=option_strings, - dest=dest, - nargs=nargs, - const=const, - default=default, - type=type, - choices=choices, - required=required, - help=help, - metavar=metavar) - - def __call__(self, parser, namespace, values, option_string=None): - setattr(namespace, self.dest, values) - - -class _StoreConstAction(Action): - - def __init__(self, - option_strings, - dest, - const, - default=None, - required=False, - help=None, - metavar=None): - super(_StoreConstAction, self).__init__( - option_strings=option_strings, - dest=dest, - nargs=0, - const=const, - default=default, - required=required, - help=help) - - def __call__(self, parser, namespace, values, option_string=None): - setattr(namespace, self.dest, self.const) - - -class _StoreTrueAction(_StoreConstAction): - - def __init__(self, - option_strings, - dest, - default=False, - required=False, - help=None): - super(_StoreTrueAction, self).__init__( - option_strings=option_strings, - dest=dest, - const=True, - default=default, - required=required, - help=help) - - -class _StoreFalseAction(_StoreConstAction): - - def __init__(self, - option_strings, - dest, - default=True, - required=False, - help=None): - super(_StoreFalseAction, self).__init__( - option_strings=option_strings, - dest=dest, - const=False, - default=default, - required=required, - help=help) - - -class _AppendAction(Action): - - def __init__(self, - option_strings, - dest, - nargs=None, - const=None, - default=None, - type=None, - choices=None, - required=False, - help=None, - metavar=None): - if nargs == 0: - raise ValueError('nargs for append actions must be > 0; if arg ' - 'strings are not supplying the value to append, ' - 'the append const action may be more appropriate') - if const is not None and nargs != OPTIONAL: - raise ValueError('nargs must be %r to supply const' % OPTIONAL) - super(_AppendAction, self).__init__( - option_strings=option_strings, - dest=dest, - nargs=nargs, - const=const, - default=default, - type=type, - choices=choices, - required=required, - help=help, - metavar=metavar) - - def __call__(self, parser, namespace, values, option_string=None): - items = _copy.copy(_ensure_value(namespace, self.dest, [])) - items.append(values) - setattr(namespace, self.dest, items) - - -class _AppendConstAction(Action): - - def __init__(self, - option_strings, - dest, - const, - default=None, - required=False, - help=None, - metavar=None): - super(_AppendConstAction, self).__init__( - option_strings=option_strings, - dest=dest, - nargs=0, - const=const, - default=default, - required=required, - help=help, - metavar=metavar) - - def __call__(self, parser, namespace, values, option_string=None): - items = _copy.copy(_ensure_value(namespace, self.dest, [])) - items.append(self.const) - setattr(namespace, self.dest, items) - - -class _CountAction(Action): - - def __init__(self, - option_strings, - dest, - default=None, - required=False, - help=None): - super(_CountAction, self).__init__( - option_strings=option_strings, - dest=dest, - nargs=0, - default=default, - required=required, - help=help) - - def __call__(self, parser, namespace, values, option_string=None): - new_count = _ensure_value(namespace, self.dest, 0) + 1 - setattr(namespace, self.dest, new_count) - - -class _HelpAction(Action): - - def __init__(self, - option_strings, - dest=SUPPRESS, - default=SUPPRESS, - help=None): - super(_HelpAction, self).__init__( - option_strings=option_strings, - dest=dest, - default=default, - nargs=0, - help=help) - - def __call__(self, parser, namespace, values, option_string=None): - parser.print_help() - parser.exit() - - -class _VersionAction(Action): - - def __init__(self, - option_strings, - version=None, - dest=SUPPRESS, - default=SUPPRESS, - help="show program's version number and exit"): - super(_VersionAction, self).__init__( - option_strings=option_strings, - dest=dest, - default=default, - nargs=0, - help=help) - self.version = version - - def __call__(self, parser, namespace, values, option_string=None): - version = self.version - if version is None: - version = parser.version - formatter = parser._get_formatter() - formatter.add_text(version) - parser.exit(message=formatter.format_help()) - - -class _SubParsersAction(Action): - - class _ChoicesPseudoAction(Action): - - def __init__(self, name, help): - sup = super(_SubParsersAction._ChoicesPseudoAction, self) - sup.__init__(option_strings=[], dest=name, help=help) - - def __init__(self, - option_strings, - prog, - parser_class, - dest=SUPPRESS, - help=None, - metavar=None): - - self._prog_prefix = prog - self._parser_class = parser_class - self._name_parser_map = {} - self._choices_actions = [] - - super(_SubParsersAction, self).__init__( - option_strings=option_strings, - dest=dest, - nargs=PARSER, - choices=self._name_parser_map, - help=help, - metavar=metavar) - - def add_parser(self, name, **kwargs): - # set prog from the existing prefix - if kwargs.get('prog') is None: - kwargs['prog'] = '%s %s' % (self._prog_prefix, name) - - # create a pseudo-action to hold the choice help - if 'help' in kwargs: - help = kwargs.pop('help') - choice_action = self._ChoicesPseudoAction(name, help) - self._choices_actions.append(choice_action) - - # create the parser and add it to the map - parser = self._parser_class(**kwargs) - self._name_parser_map[name] = parser - return parser - - def _get_subactions(self): - return self._choices_actions - - def __call__(self, parser, namespace, values, option_string=None): - parser_name = values[0] - arg_strings = values[1:] - - # set the parser name if requested - if self.dest is not SUPPRESS: - setattr(namespace, self.dest, parser_name) - - # select the parser - try: - parser = self._name_parser_map[parser_name] - except KeyError: - tup = parser_name, ', '.join(self._name_parser_map) - msg = _('unknown parser %r (choices: %s)' % tup) - raise ArgumentError(self, msg) - - # parse all the remaining options into the namespace - # store any unrecognized options on the object, so that the top - # level parser can decide what to do with them - namespace, arg_strings = parser.parse_known_args(arg_strings, namespace) - if arg_strings: - vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, []) - getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) - - -# ============== -# Type classes -# ============== - -class FileType(object): - """Factory for creating file object types - - Instances of FileType are typically passed as type= arguments to the - ArgumentParser add_argument() method. - - Keyword Arguments: - - mode -- A string indicating how the file is to be opened. Accepts the - same values as the builtin open() function. - - bufsize -- The file's desired buffer size. Accepts the same values as - the builtin open() function. - """ - - def __init__(self, mode='r', bufsize=None): - self._mode = mode - self._bufsize = bufsize - - def __call__(self, string): - # the special argument "-" means sys.std{in,out} - if string == '-': - if 'r' in self._mode: - return _sys.stdin - elif 'w' in self._mode: - return _sys.stdout - else: - msg = _('argument "-" with mode %r' % self._mode) - raise ValueError(msg) - - # all other arguments are used as file names - if self._bufsize: - return open(string, self._mode, self._bufsize) - else: - return open(string, self._mode) - - def __repr__(self): - args = [self._mode, self._bufsize] - args_str = ', '.join([repr(arg) for arg in args if arg is not None]) - return '%s(%s)' % (type(self).__name__, args_str) - -# =========================== -# Optional and Positional Parsing -# =========================== - -class Namespace(_AttributeHolder): - """Simple object for storing attributes. - - Implements equality by attribute names and values, and provides a simple - string representation. - """ - - def __init__(self, **kwargs): - for name in kwargs: - setattr(self, name, kwargs[name]) - - __hash__ = None - - def __eq__(self, other): - return vars(self) == vars(other) - - def __ne__(self, other): - return not (self == other) - - def __contains__(self, key): - return key in self.__dict__ - - -class _ActionsContainer(object): - - def __init__(self, - description, - prefix_chars, - argument_default, - conflict_handler): - super(_ActionsContainer, self).__init__() - - self.description = description - self.argument_default = argument_default - self.prefix_chars = prefix_chars - self.conflict_handler = conflict_handler - - # set up registries - self._registries = {} - - # register actions - self.register('action', None, _StoreAction) - self.register('action', 'store', _StoreAction) - self.register('action', 'store_const', _StoreConstAction) - self.register('action', 'store_true', _StoreTrueAction) - self.register('action', 'store_false', _StoreFalseAction) - self.register('action', 'append', _AppendAction) - self.register('action', 'append_const', _AppendConstAction) - self.register('action', 'count', _CountAction) - self.register('action', 'help', _HelpAction) - self.register('action', 'version', _VersionAction) - self.register('action', 'parsers', _SubParsersAction) - - # raise an exception if the conflict handler is invalid - self._get_handler() - - # action storage - self._actions = [] - self._option_string_actions = {} - - # groups - self._action_groups = [] - self._mutually_exclusive_groups = [] - - # defaults storage - self._defaults = {} - - # determines whether an "option" looks like a negative number - self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$') - - # whether or not there are any optionals that look like negative - # numbers -- uses a list so it can be shared and edited - self._has_negative_number_optionals = [] - - # ==================== - # Registration methods - # ==================== - def register(self, registry_name, value, object): - registry = self._registries.setdefault(registry_name, {}) - registry[value] = object - - def _registry_get(self, registry_name, value, default=None): - return self._registries[registry_name].get(value, default) - - # ================================== - # Namespace default accessor methods - # ================================== - def set_defaults(self, **kwargs): - self._defaults.update(kwargs) - - # if these defaults match any existing arguments, replace - # the previous default on the object with the new one - for action in self._actions: - if action.dest in kwargs: - action.default = kwargs[action.dest] - - def get_default(self, dest): - for action in self._actions: - if action.dest == dest and action.default is not None: - return action.default - return self._defaults.get(dest, None) - - - # ======================= - # Adding argument actions - # ======================= - def add_argument(self, *args, **kwargs): - """ - add_argument(dest, ..., name=value, ...) - add_argument(option_string, option_string, ..., name=value, ...) - """ - - # if no positional args are supplied or only one is supplied and - # it doesn't look like an option string, parse a positional - # argument - chars = self.prefix_chars - if not args or len(args) == 1 and args[0][0] not in chars: - if args and 'dest' in kwargs: - raise ValueError('dest supplied twice for positional argument') - kwargs = self._get_positional_kwargs(*args, **kwargs) - - # otherwise, we're adding an optional argument - else: - kwargs = self._get_optional_kwargs(*args, **kwargs) - - # if no default was supplied, use the parser-level default - if 'default' not in kwargs: - dest = kwargs['dest'] - if dest in self._defaults: - kwargs['default'] = self._defaults[dest] - elif self.argument_default is not None: - kwargs['default'] = self.argument_default - - # create the action object, and add it to the parser - action_class = self._pop_action_class(kwargs) - if not _callable(action_class): - raise ValueError('unknown action "%s"' % action_class) - action = action_class(**kwargs) - - # raise an error if the action type is not callable - type_func = self._registry_get('type', action.type, action.type) - if not _callable(type_func): - raise ValueError('%r is not callable' % type_func) - - return self._add_action(action) - - def add_argument_group(self, *args, **kwargs): - group = _ArgumentGroup(self, *args, **kwargs) - self._action_groups.append(group) - return group - - def add_mutually_exclusive_group(self, **kwargs): - group = _MutuallyExclusiveGroup(self, **kwargs) - self._mutually_exclusive_groups.append(group) - return group - - def _add_action(self, action): - # resolve any conflicts - self._check_conflict(action) - - # add to actions list - self._actions.append(action) - action.container = self - - # index the action by any option strings it has - for option_string in action.option_strings: - self._option_string_actions[option_string] = action - - # set the flag if any option strings look like negative numbers - for option_string in action.option_strings: - if self._negative_number_matcher.match(option_string): - if not self._has_negative_number_optionals: - self._has_negative_number_optionals.append(True) - - # return the created action - return action - - def _remove_action(self, action): - self._actions.remove(action) - - def _add_container_actions(self, container): - # collect groups by titles - title_group_map = {} - for group in self._action_groups: - if group.title in title_group_map: - msg = _('cannot merge actions - two groups are named %r') - raise ValueError(msg % (group.title)) - title_group_map[group.title] = group - - # map each action to its group - group_map = {} - for group in container._action_groups: - - # if a group with the title exists, use that, otherwise - # create a new group matching the container's group - if group.title not in title_group_map: - title_group_map[group.title] = self.add_argument_group( - title=group.title, - description=group.description, - conflict_handler=group.conflict_handler) - - # map the actions to their new group - for action in group._group_actions: - group_map[action] = title_group_map[group.title] - - # add container's mutually exclusive groups - # NOTE: if add_mutually_exclusive_group ever gains title= and - # description= then this code will need to be expanded as above - for group in container._mutually_exclusive_groups: - mutex_group = self.add_mutually_exclusive_group( - required=group.required) - - # map the actions to their new mutex group - for action in group._group_actions: - group_map[action] = mutex_group - - # add all actions to this container or their group - for action in container._actions: - group_map.get(action, self)._add_action(action) - - def _get_positional_kwargs(self, dest, **kwargs): - # make sure required is not specified - if 'required' in kwargs: - msg = _("'required' is an invalid argument for positionals") - raise TypeError(msg) - - # mark positional arguments as required if at least one is - # always required - if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]: - kwargs['required'] = True - if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs: - kwargs['required'] = True - - # return the keyword arguments with no option strings - return dict(kwargs, dest=dest, option_strings=[]) - - def _get_optional_kwargs(self, *args, **kwargs): - # determine short and long option strings - option_strings = [] - long_option_strings = [] - for option_string in args: - # error on strings that don't start with an appropriate prefix - if not option_string[0] in self.prefix_chars: - msg = _('invalid option string %r: ' - 'must start with a character %r') - tup = option_string, self.prefix_chars - raise ValueError(msg % tup) - - # strings starting with two prefix characters are long options - option_strings.append(option_string) - if option_string[0] in self.prefix_chars: - if len(option_string) > 1: - if option_string[1] in self.prefix_chars: - long_option_strings.append(option_string) - - # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' - dest = kwargs.pop('dest', None) - if dest is None: - if long_option_strings: - dest_option_string = long_option_strings[0] - else: - dest_option_string = option_strings[0] - dest = dest_option_string.lstrip(self.prefix_chars) - if not dest: - msg = _('dest= is required for options like %r') - raise ValueError(msg % option_string) - dest = dest.replace('-', '_') - - # return the updated keyword arguments - return dict(kwargs, dest=dest, option_strings=option_strings) - - def _pop_action_class(self, kwargs, default=None): - action = kwargs.pop('action', default) - return self._registry_get('action', action, action) - - def _get_handler(self): - # determine function from conflict handler string - handler_func_name = '_handle_conflict_%s' % self.conflict_handler - try: - return getattr(self, handler_func_name) - except AttributeError: - msg = _('invalid conflict_resolution value: %r') - raise ValueError(msg % self.conflict_handler) - - def _check_conflict(self, action): - - # find all options that conflict with this option - confl_optionals = [] - for option_string in action.option_strings: - if option_string in self._option_string_actions: - confl_optional = self._option_string_actions[option_string] - confl_optionals.append((option_string, confl_optional)) - - # resolve any conflicts - if confl_optionals: - conflict_handler = self._get_handler() - conflict_handler(action, confl_optionals) - - def _handle_conflict_error(self, action, conflicting_actions): - message = _('conflicting option string(s): %s') - conflict_string = ', '.join([option_string - for option_string, action - in conflicting_actions]) - raise ArgumentError(action, message % conflict_string) - - def _handle_conflict_resolve(self, action, conflicting_actions): - - # remove all conflicting options - for option_string, action in conflicting_actions: - - # remove the conflicting option - action.option_strings.remove(option_string) - self._option_string_actions.pop(option_string, None) - - # if the option now has no option string, remove it from the - # container holding it - if not action.option_strings: - action.container._remove_action(action) - - -class _ArgumentGroup(_ActionsContainer): - - def __init__(self, container, title=None, description=None, **kwargs): - # add any missing keyword arguments by checking the container - update = kwargs.setdefault - update('conflict_handler', container.conflict_handler) - update('prefix_chars', container.prefix_chars) - update('argument_default', container.argument_default) - super_init = super(_ArgumentGroup, self).__init__ - super_init(description=description, **kwargs) - - # group attributes - self.title = title - self._group_actions = [] - - # share most attributes with the container - self._registries = container._registries - self._actions = container._actions - self._option_string_actions = container._option_string_actions - self._defaults = container._defaults - self._has_negative_number_optionals = \ - container._has_negative_number_optionals - - def _add_action(self, action): - action = super(_ArgumentGroup, self)._add_action(action) - self._group_actions.append(action) - return action - - def _remove_action(self, action): - super(_ArgumentGroup, self)._remove_action(action) - self._group_actions.remove(action) - - -class _MutuallyExclusiveGroup(_ArgumentGroup): - - def __init__(self, container, required=False): - super(_MutuallyExclusiveGroup, self).__init__(container) - self.required = required - self._container = container - - def _add_action(self, action): - if action.required: - msg = _('mutually exclusive arguments must be optional') - raise ValueError(msg) - action = self._container._add_action(action) - self._group_actions.append(action) - return action - - def _remove_action(self, action): - self._container._remove_action(action) - self._group_actions.remove(action) - - -class ArgumentParser(_AttributeHolder, _ActionsContainer): - """Object for parsing command line strings into Python objects. - - Keyword Arguments: - - prog -- The name of the program (default: sys.argv[0]) - - usage -- A usage message (default: auto-generated from arguments) - - description -- A description of what the program does - - epilog -- Text following the argument descriptions - - parents -- Parsers whose arguments should be copied into this one - - formatter_class -- HelpFormatter class for printing help messages - - prefix_chars -- Characters that prefix optional arguments - - fromfile_prefix_chars -- Characters that prefix files containing - additional arguments - - argument_default -- The default value for all arguments - - conflict_handler -- String indicating how to handle conflicts - - add_help -- Add a -h/-help option - """ - - def __init__(self, - prog=None, - usage=None, - description=None, - epilog=None, - version=None, - parents=[], - formatter_class=HelpFormatter, - prefix_chars='-', - fromfile_prefix_chars=None, - argument_default=None, - conflict_handler='error', - add_help=True): - - if version is not None: - import warnings - warnings.warn( - """The "version" argument to ArgumentParser is deprecated. """ - """Please use """ - """"add_argument(..., action='version', version="N", ...)" """ - """instead""", DeprecationWarning) - - superinit = super(ArgumentParser, self).__init__ - superinit(description=description, - prefix_chars=prefix_chars, - argument_default=argument_default, - conflict_handler=conflict_handler) - - # default setting for prog - if prog is None: - prog = _os.path.basename(_sys.argv[0]) - - self.prog = prog - self.usage = usage - self.epilog = epilog - self.version = version - self.formatter_class = formatter_class - self.fromfile_prefix_chars = fromfile_prefix_chars - self.add_help = add_help - - add_group = self.add_argument_group - self._positionals = add_group(_('positional arguments')) - self._optionals = add_group(_('optional arguments')) - self._subparsers = None - - # register types - def identity(string): - return string - self.register('type', None, identity) - - # add help and version arguments if necessary - # (using explicit default to override global argument_default) - if '-' in prefix_chars: - default_prefix = '-' - else: - default_prefix = prefix_chars[0] - if self.add_help: - self.add_argument( - default_prefix+'h', default_prefix*2+'help', - action='help', default=SUPPRESS, - help=_('show this help message and exit')) - if self.version: - self.add_argument( - default_prefix+'v', default_prefix*2+'version', - action='version', default=SUPPRESS, - version=self.version, - help=_("show program's version number and exit")) - - # add parent arguments and defaults - for parent in parents: - self._add_container_actions(parent) - try: - defaults = parent._defaults - except AttributeError: - pass - else: - self._defaults.update(defaults) - - # ======================= - # Pretty __repr__ methods - # ======================= - def _get_kwargs(self): - names = [ - 'prog', - 'usage', - 'description', - 'version', - 'formatter_class', - 'conflict_handler', - 'add_help', - ] - return [(name, getattr(self, name)) for name in names] - - # ================================== - # Optional/Positional adding methods - # ================================== - def add_subparsers(self, **kwargs): - if self._subparsers is not None: - self.error(_('cannot have multiple subparser arguments')) - - # add the parser class to the arguments if it's not present - kwargs.setdefault('parser_class', type(self)) - - if 'title' in kwargs or 'description' in kwargs: - title = _(kwargs.pop('title', 'subcommands')) - description = _(kwargs.pop('description', None)) - self._subparsers = self.add_argument_group(title, description) - else: - self._subparsers = self._positionals - - # prog defaults to the usage message of this parser, skipping - # optional arguments and with no "usage:" prefix - if kwargs.get('prog') is None: - formatter = self._get_formatter() - positionals = self._get_positional_actions() - groups = self._mutually_exclusive_groups - formatter.add_usage(self.usage, positionals, groups, '') - kwargs['prog'] = formatter.format_help().strip() - - # create the parsers action and add it to the positionals list - parsers_class = self._pop_action_class(kwargs, 'parsers') - action = parsers_class(option_strings=[], **kwargs) - self._subparsers._add_action(action) - - # return the created parsers action - return action - - def _add_action(self, action): - if action.option_strings: - self._optionals._add_action(action) - else: - self._positionals._add_action(action) - return action - - def _get_optional_actions(self): - return [action - for action in self._actions - if action.option_strings] - - def _get_positional_actions(self): - return [action - for action in self._actions - if not action.option_strings] - - # ===================================== - # Command line argument parsing methods - # ===================================== - def parse_args(self, args=None, namespace=None): - args, argv = self.parse_known_args(args, namespace) - if argv: - msg = _('unrecognized arguments: %s') - self.error(msg % ' '.join(argv)) - return args - - def parse_known_args(self, args=None, namespace=None): - # args default to the system args - if args is None: - args = _sys.argv[1:] - - # default Namespace built from parser defaults - if namespace is None: - namespace = Namespace() - - # add any action defaults that aren't present - for action in self._actions: - if action.dest is not SUPPRESS: - if not hasattr(namespace, action.dest): - if action.default is not SUPPRESS: - default = action.default - if isinstance(action.default, basestring): - default = self._get_value(action, default) - setattr(namespace, action.dest, default) - - # add any parser defaults that aren't present - for dest in self._defaults: - if not hasattr(namespace, dest): - setattr(namespace, dest, self._defaults[dest]) - - # parse the arguments and exit if there are any errors - try: - namespace, args = self._parse_known_args(args, namespace) - if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR): - args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) - delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) - return namespace, args - except ArgumentError: - err = _sys.exc_info()[1] - self.error(str(err)) - - def _parse_known_args(self, arg_strings, namespace): - # replace arg strings that are file references - if self.fromfile_prefix_chars is not None: - arg_strings = self._read_args_from_files(arg_strings) - - # map all mutually exclusive arguments to the other arguments - # they can't occur with - action_conflicts = {} - for mutex_group in self._mutually_exclusive_groups: - group_actions = mutex_group._group_actions - for i, mutex_action in enumerate(mutex_group._group_actions): - conflicts = action_conflicts.setdefault(mutex_action, []) - conflicts.extend(group_actions[:i]) - conflicts.extend(group_actions[i + 1:]) - - # find all option indices, and determine the arg_string_pattern - # which has an 'O' if there is an option at an index, - # an 'A' if there is an argument, or a '-' if there is a '--' - option_string_indices = {} - arg_string_pattern_parts = [] - arg_strings_iter = iter(arg_strings) - for i, arg_string in enumerate(arg_strings_iter): - - # all args after -- are non-options - if arg_string == '--': - arg_string_pattern_parts.append('-') - for arg_string in arg_strings_iter: - arg_string_pattern_parts.append('A') - - # otherwise, add the arg to the arg strings - # and note the index if it was an option - else: - option_tuple = self._parse_optional(arg_string) - if option_tuple is None: - pattern = 'A' - else: - option_string_indices[i] = option_tuple - pattern = 'O' - arg_string_pattern_parts.append(pattern) - - # join the pieces together to form the pattern - arg_strings_pattern = ''.join(arg_string_pattern_parts) - - # converts arg strings to the appropriate and then takes the action - seen_actions = set() - seen_non_default_actions = set() - - def take_action(action, argument_strings, option_string=None): - seen_actions.add(action) - argument_values = self._get_values(action, argument_strings) - - # error if this argument is not allowed with other previously - # seen arguments, assuming that actions that use the default - # value don't really count as "present" - if argument_values is not action.default: - seen_non_default_actions.add(action) - for conflict_action in action_conflicts.get(action, []): - if conflict_action in seen_non_default_actions: - msg = _('not allowed with argument %s') - action_name = _get_action_name(conflict_action) - raise ArgumentError(action, msg % action_name) - - # take the action if we didn't receive a SUPPRESS value - # (e.g. from a default) - if argument_values is not SUPPRESS: - action(self, namespace, argument_values, option_string) - - # function to convert arg_strings into an optional action - def consume_optional(start_index): - - # get the optional identified at this index - option_tuple = option_string_indices[start_index] - action, option_string, explicit_arg = option_tuple - - # identify additional optionals in the same arg string - # (e.g. -xyz is the same as -x -y -z if no args are required) - match_argument = self._match_argument - action_tuples = [] - while True: - - # if we found no optional action, skip it - if action is None: - extras.append(arg_strings[start_index]) - return start_index + 1 - - # if there is an explicit argument, try to match the - # optional's string arguments to only this - if explicit_arg is not None: - arg_count = match_argument(action, 'A') - - # if the action is a single-dash option and takes no - # arguments, try to parse more single-dash options out - # of the tail of the option string - chars = self.prefix_chars - if arg_count == 0 and option_string[1] not in chars: - action_tuples.append((action, [], option_string)) - char = option_string[0] - option_string = char + explicit_arg[0] - new_explicit_arg = explicit_arg[1:] or None - optionals_map = self._option_string_actions - if option_string in optionals_map: - action = optionals_map[option_string] - explicit_arg = new_explicit_arg - else: - msg = _('ignored explicit argument %r') - raise ArgumentError(action, msg % explicit_arg) - - # if the action expect exactly one argument, we've - # successfully matched the option; exit the loop - elif arg_count == 1: - stop = start_index + 1 - args = [explicit_arg] - action_tuples.append((action, args, option_string)) - break - - # error if a double-dash option did not use the - # explicit argument - else: - msg = _('ignored explicit argument %r') - raise ArgumentError(action, msg % explicit_arg) - - # if there is no explicit argument, try to match the - # optional's string arguments with the following strings - # if successful, exit the loop - else: - start = start_index + 1 - selected_patterns = arg_strings_pattern[start:] - arg_count = match_argument(action, selected_patterns) - stop = start + arg_count - args = arg_strings[start:stop] - action_tuples.append((action, args, option_string)) - break - - # add the Optional to the list and return the index at which - # the Optional's string args stopped - assert action_tuples - for action, args, option_string in action_tuples: - take_action(action, args, option_string) - return stop - - # the list of Positionals left to be parsed; this is modified - # by consume_positionals() - positionals = self._get_positional_actions() - - # function to convert arg_strings into positional actions - def consume_positionals(start_index): - # match as many Positionals as possible - match_partial = self._match_arguments_partial - selected_pattern = arg_strings_pattern[start_index:] - arg_counts = match_partial(positionals, selected_pattern) - - # slice off the appropriate arg strings for each Positional - # and add the Positional and its args to the list - for action, arg_count in zip(positionals, arg_counts): - args = arg_strings[start_index: start_index + arg_count] - start_index += arg_count - take_action(action, args) - - # slice off the Positionals that we just parsed and return the - # index at which the Positionals' string args stopped - positionals[:] = positionals[len(arg_counts):] - return start_index - - # consume Positionals and Optionals alternately, until we have - # passed the last option string - extras = [] - start_index = 0 - if option_string_indices: - max_option_string_index = max(option_string_indices) - else: - max_option_string_index = -1 - while start_index <= max_option_string_index: - - # consume any Positionals preceding the next option - next_option_string_index = min([ - index - for index in option_string_indices - if index >= start_index]) - if start_index != next_option_string_index: - positionals_end_index = consume_positionals(start_index) - - # only try to parse the next optional if we didn't consume - # the option string during the positionals parsing - if positionals_end_index > start_index: - start_index = positionals_end_index - continue - else: - start_index = positionals_end_index - - # if we consumed all the positionals we could and we're not - # at the index of an option string, there were extra arguments - if start_index not in option_string_indices: - strings = arg_strings[start_index:next_option_string_index] - extras.extend(strings) - start_index = next_option_string_index - - # consume the next optional and any arguments for it - start_index = consume_optional(start_index) - - # consume any positionals following the last Optional - stop_index = consume_positionals(start_index) - - # if we didn't consume all the argument strings, there were extras - extras.extend(arg_strings[stop_index:]) - - # if we didn't use all the Positional objects, there were too few - # arg strings supplied. - if positionals: - self.error(_('too few arguments')) - - # make sure all required actions were present - for action in self._actions: - if action.required: - if action not in seen_actions: - name = _get_action_name(action) - self.error(_('argument %s is required') % name) - - # make sure all required groups had one option present - for group in self._mutually_exclusive_groups: - if group.required: - for action in group._group_actions: - if action in seen_non_default_actions: - break - - # if no actions were used, report the error - else: - names = [_get_action_name(action) - for action in group._group_actions - if action.help is not SUPPRESS] - msg = _('one of the arguments %s is required') - self.error(msg % ' '.join(names)) - - # return the updated namespace and the extra arguments - return namespace, extras - - def _read_args_from_files(self, arg_strings): - # expand arguments referencing files - new_arg_strings = [] - for arg_string in arg_strings: - - # for regular arguments, just add them back into the list - if arg_string[0] not in self.fromfile_prefix_chars: - new_arg_strings.append(arg_string) - - # replace arguments referencing files with the file content - else: - try: - args_file = open(arg_string[1:]) - try: - arg_strings = [] - for arg_line in args_file.read().splitlines(): - for arg in self.convert_arg_line_to_args(arg_line): - arg_strings.append(arg) - arg_strings = self._read_args_from_files(arg_strings) - new_arg_strings.extend(arg_strings) - finally: - args_file.close() - except IOError: - err = _sys.exc_info()[1] - self.error(str(err)) - - # return the modified argument list - return new_arg_strings - - def convert_arg_line_to_args(self, arg_line): - return [arg_line] - - def _match_argument(self, action, arg_strings_pattern): - # match the pattern for this action to the arg strings - nargs_pattern = self._get_nargs_pattern(action) - match = _re.match(nargs_pattern, arg_strings_pattern) - - # raise an exception if we weren't able to find a match - if match is None: - nargs_errors = { - None: _('expected one argument'), - OPTIONAL: _('expected at most one argument'), - ONE_OR_MORE: _('expected at least one argument'), - } - default = _('expected %s argument(s)') % action.nargs - msg = nargs_errors.get(action.nargs, default) - raise ArgumentError(action, msg) - - # return the number of arguments matched - return len(match.group(1)) - - def _match_arguments_partial(self, actions, arg_strings_pattern): - # progressively shorten the actions list by slicing off the - # final actions until we find a match - result = [] - for i in range(len(actions), 0, -1): - actions_slice = actions[:i] - pattern = ''.join([self._get_nargs_pattern(action) - for action in actions_slice]) - match = _re.match(pattern, arg_strings_pattern) - if match is not None: - result.extend([len(string) for string in match.groups()]) - break - - # return the list of arg string counts - return result - - def _parse_optional(self, arg_string): - # if it's an empty string, it was meant to be a positional - if not arg_string: - return None - - # if it doesn't start with a prefix, it was meant to be positional - if not arg_string[0] in self.prefix_chars: - return None - - # if the option string is present in the parser, return the action - if arg_string in self._option_string_actions: - action = self._option_string_actions[arg_string] - return action, arg_string, None - - # if it's just a single character, it was meant to be positional - if len(arg_string) == 1: - return None - - # if the option string before the "=" is present, return the action - if '=' in arg_string: - option_string, explicit_arg = arg_string.split('=', 1) - if option_string in self._option_string_actions: - action = self._option_string_actions[option_string] - return action, option_string, explicit_arg - - # search through all possible prefixes of the option string - # and all actions in the parser for possible interpretations - option_tuples = self._get_option_tuples(arg_string) - - # if multiple actions match, the option string was ambiguous - if len(option_tuples) > 1: - options = ', '.join([option_string - for action, option_string, explicit_arg in option_tuples]) - tup = arg_string, options - self.error(_('ambiguous option: %s could match %s') % tup) - - # if exactly one action matched, this segmentation is good, - # so return the parsed action - elif len(option_tuples) == 1: - option_tuple, = option_tuples - return option_tuple - - # if it was not found as an option, but it looks like a negative - # number, it was meant to be positional - # unless there are negative-number-like options - if self._negative_number_matcher.match(arg_string): - if not self._has_negative_number_optionals: - return None - - # if it contains a space, it was meant to be a positional - if ' ' in arg_string: - return None - - # it was meant to be an optional but there is no such option - # in this parser (though it might be a valid option in a subparser) - return None, arg_string, None - - def _get_option_tuples(self, option_string): - result = [] - - # option strings starting with two prefix characters are only - # split at the '=' - chars = self.prefix_chars - if option_string[0] in chars and option_string[1] in chars: - if '=' in option_string: - option_prefix, explicit_arg = option_string.split('=', 1) - else: - option_prefix = option_string - explicit_arg = None - for option_string in self._option_string_actions: - if option_string.startswith(option_prefix): - action = self._option_string_actions[option_string] - tup = action, option_string, explicit_arg - result.append(tup) - - # single character options can be concatenated with their arguments - # but multiple character options always have to have their argument - # separate - elif option_string[0] in chars and option_string[1] not in chars: - option_prefix = option_string - explicit_arg = None - short_option_prefix = option_string[:2] - short_explicit_arg = option_string[2:] - - for option_string in self._option_string_actions: - if option_string == short_option_prefix: - action = self._option_string_actions[option_string] - tup = action, option_string, short_explicit_arg - result.append(tup) - elif option_string.startswith(option_prefix): - action = self._option_string_actions[option_string] - tup = action, option_string, explicit_arg - result.append(tup) - - # shouldn't ever get here - else: - self.error(_('unexpected option string: %s') % option_string) - - # return the collected option tuples - return result - - def _get_nargs_pattern(self, action): - # in all examples below, we have to allow for '--' args - # which are represented as '-' in the pattern - nargs = action.nargs - - # the default (None) is assumed to be a single argument - if nargs is None: - nargs_pattern = '(-*A-*)' - - # allow zero or one arguments - elif nargs == OPTIONAL: - nargs_pattern = '(-*A?-*)' - - # allow zero or more arguments - elif nargs == ZERO_OR_MORE: - nargs_pattern = '(-*[A-]*)' - - # allow one or more arguments - elif nargs == ONE_OR_MORE: - nargs_pattern = '(-*A[A-]*)' - - # allow any number of options or arguments - elif nargs == REMAINDER: - nargs_pattern = '([-AO]*)' - - # allow one argument followed by any number of options or arguments - elif nargs == PARSER: - nargs_pattern = '(-*A[-AO]*)' - - # all others should be integers - else: - nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs) - - # if this is an optional action, -- is not allowed - if action.option_strings: - nargs_pattern = nargs_pattern.replace('-*', '') - nargs_pattern = nargs_pattern.replace('-', '') - - # return the pattern - return nargs_pattern - - # ======================== - # Value conversion methods - # ======================== - def _get_values(self, action, arg_strings): - # for everything but PARSER args, strip out '--' - if action.nargs not in [PARSER, REMAINDER]: - arg_strings = [s for s in arg_strings if s != '--'] - - # optional argument produces a default when not present - if not arg_strings and action.nargs == OPTIONAL: - if action.option_strings: - value = action.const - else: - value = action.default - if isinstance(value, basestring): - value = self._get_value(action, value) - self._check_value(action, value) - - # when nargs='*' on a positional, if there were no command-line - # args, use the default if it is anything other than None - elif (not arg_strings and action.nargs == ZERO_OR_MORE and - not action.option_strings): - if action.default is not None: - value = action.default - else: - value = arg_strings - self._check_value(action, value) - - # single argument or optional argument produces a single value - elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]: - arg_string, = arg_strings - value = self._get_value(action, arg_string) - self._check_value(action, value) - - # REMAINDER arguments convert all values, checking none - elif action.nargs == REMAINDER: - value = [self._get_value(action, v) for v in arg_strings] - - # PARSER arguments convert all values, but check only the first - elif action.nargs == PARSER: - value = [self._get_value(action, v) for v in arg_strings] - self._check_value(action, value[0]) - - # all other types of nargs produce a list - else: - value = [self._get_value(action, v) for v in arg_strings] - for v in value: - self._check_value(action, v) - - # return the converted value - return value - - def _get_value(self, action, arg_string): - type_func = self._registry_get('type', action.type, action.type) - if not _callable(type_func): - msg = _('%r is not callable') - raise ArgumentError(action, msg % type_func) - - # convert the value to the appropriate type - try: - result = type_func(arg_string) - - # ArgumentTypeErrors indicate errors - except ArgumentTypeError: - name = getattr(action.type, '__name__', repr(action.type)) - msg = str(_sys.exc_info()[1]) - raise ArgumentError(action, msg) - - # TypeErrors or ValueErrors also indicate errors - except (TypeError, ValueError): - name = getattr(action.type, '__name__', repr(action.type)) - msg = _('invalid %s value: %r') - raise ArgumentError(action, msg % (name, arg_string)) - - # return the converted value - return result - - def _check_value(self, action, value): - # converted value must be one of the choices (if specified) - if action.choices is not None and value not in action.choices: - tup = value, ', '.join(map(repr, action.choices)) - msg = _('invalid choice: %r (choose from %s)') % tup - raise ArgumentError(action, msg) - - # ======================= - # Help-formatting methods - # ======================= - def format_usage(self): - formatter = self._get_formatter() - formatter.add_usage(self.usage, self._actions, - self._mutually_exclusive_groups) - return formatter.format_help() - - def format_help(self): - formatter = self._get_formatter() - - # usage - formatter.add_usage(self.usage, self._actions, - self._mutually_exclusive_groups) - - # description - formatter.add_text(self.description) - - # positionals, optionals and user-defined groups - for action_group in self._action_groups: - formatter.start_section(action_group.title) - formatter.add_text(action_group.description) - formatter.add_arguments(action_group._group_actions) - formatter.end_section() - - # epilog - formatter.add_text(self.epilog) - - # determine help from format above - return formatter.format_help() - - def format_version(self): - import warnings - warnings.warn( - 'The format_version method is deprecated -- the "version" ' - 'argument to ArgumentParser is no longer supported.', - DeprecationWarning) - formatter = self._get_formatter() - formatter.add_text(self.version) - return formatter.format_help() - - def _get_formatter(self): - return self.formatter_class(prog=self.prog) - - # ===================== - # Help-printing methods - # ===================== - def print_usage(self, file=None): - if file is None: - file = _sys.stdout - self._print_message(self.format_usage(), file) - - def print_help(self, file=None): - if file is None: - file = _sys.stdout - self._print_message(self.format_help(), file) - - def print_version(self, file=None): - import warnings - warnings.warn( - 'The print_version method is deprecated -- the "version" ' - 'argument to ArgumentParser is no longer supported.', - DeprecationWarning) - self._print_message(self.format_version(), file) - - def _print_message(self, message, file=None): - if message: - if file is None: - file = _sys.stderr - file.write(message) - - # =============== - # Exiting methods - # =============== - def exit(self, status=0, message=None): - if message: - self._print_message(message, _sys.stderr) - _sys.exit(status) - - def error(self, message): - """error(message: string) - - Prints a usage message incorporating the message to stderr and - exits. - - If you override this in a subclass, it should not return -- it - should either exit or raise an exception. - """ - self.print_usage(_sys.stderr) - self.exit(2, _('%s: error: %s\n') % (self.prog, message)) diff --git a/ete2/_ph.py b/ete2/_ph.py deleted file mode 100644 index 772a231..0000000 --- a/ete2/_ph.py +++ /dev/null @@ -1,144 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" - #START_LICENSE########################################################### -# -# -# -# #END_LICENSE############################################################# - -''' I use this module to check for newer versions of ETE ''' - -import urllib2 as url - -try: - from ete2 import __ETEID__ -except ImportError: - __ETEID__ = "Unknown" - -try: - from ete2 import __VERSION__ -except ImportError: - __VERSION__ = "Unknown" - -def call(): - print " == Calling home...", - try: - f = url.urlopen('http://ete.cgenomics.org/et_phone_home.php?VERSION=%s&ID=%s' - %(__VERSION__, __ETEID__)) - except: - print "No answer :(" - else: - print "Got answer!" - print f.read() - - module_name = __name__.split(".")[0] - try: - f = url.urlopen('http://ete.cgenomics.org/releases/ete2/%s.latest' - %module_name) - except: - latest = None - else: - latest = int(f.read()) - - try: - current = int(__VERSION__.split("rev")[1]) - except (IndexError, ValueError): - current = None - - if not latest: - print "I could not find data about your version [%s]" %module_name - print "Are you ok?" - elif not current: - print "I could not determine your version [%s]" %module_name - print "Are you ok?" - print "Latest stable ETE version is", latest - elif latest > current: - print "You look a bit old." - print "A newer version is available: rev%s" %latest - print "Use 'easy_install -U %s' to upgrade" %module_name - else: - print "I see you are in shape." - print "No updates are available." - try: - msg = raw_input("\n == Do you want to leave any message?\n(Press enter to finish)\n\n").strip() - except KeyboardInterrupt: - msg = None - - if msg: - msg = url.quote(msg) - try: - f = url.urlopen('http://ete.cgenomics.org/et_phone_home.php?VERSION=%s&ID=%s&MSG=%s' - %(__VERSION__, __ETEID__, msg)) - except: - print "Message could be delivered :(" - else: - print f.read() - -def new_version(module_name=None, current=None): - if not module_name: - module_name = __name__.split(".")[0] - try: - f = url.urlopen('http://ete.cgenomics.org/releases/ete2/%s.latest' - %module_name) - except: - latest = None - else: - latest = int(f.read()) - - news_url = 'http://ete.cgenomics.org/releases/ete2/%s.latest_news' %module_name - msg = read_content(news_url) - - if not current: - try: - current = int(__VERSION__.split("rev")[1]) - except (IndexError, ValueError): - current = None - - return current, latest, msg - -def read_content(address): - try: - f = url.urlopen(address) - except: - return None - else: - return f.read() - diff --git a/ete2/_ph.pyc b/ete2/_ph.pyc deleted file mode 100644 index 511e272..0000000 Binary files a/ete2/_ph.pyc and /dev/null differ diff --git a/ete2/clustering/__init__.py b/ete2/clustering/__init__.py deleted file mode 100644 index 4cce55c..0000000 --- a/ete2/clustering/__init__.py +++ /dev/null @@ -1,43 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -from clustertree import * -__all__ = clustertree.__all__ diff --git a/ete2/clustering/__init__.pyc b/ete2/clustering/__init__.pyc deleted file mode 100644 index 2f6abb7..0000000 Binary files a/ete2/clustering/__init__.pyc and /dev/null differ diff --git a/ete2/clustering/clustertree.py b/ete2/clustering/clustertree.py deleted file mode 100644 index 91878fb..0000000 --- a/ete2/clustering/clustertree.py +++ /dev/null @@ -1,257 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -from sys import stderr -import numpy -import clustvalidation -from numpy import nan as NaN # Missing values are saved as NaN values -from ete2.coretype.tree import _translate_nodes -from ete2 import TreeNode, ArrayTable - -__all__ = ["ClusterNode", "ClusterTree"] - -class ClusterNode(TreeNode): - """ Creates a new Cluster Tree object, which is a collection - of ClusterNode instances connected in a hierarchical way, and - representing a clustering result. - - a newick file or string can be passed as the first argument. An - ArrayTable file or instance can be passed as a second argument. - - Examples: - t1 = Tree() # creates an empty tree - t2 = Tree( '(A:1,(B:1,(C:1,D:1):0.5):0.5);' ) - t3 = Tree( '/home/user/myNewickFile.txt' ) - """ - - def _set_forbidden(self, value): - raise ValueError, "This attribute can not be manually set." - - def _get_intra(self): - if self._silhouette == None: - self.get_silhouette() - return self._intracluster_dist - - def _get_inter(self): - if self._silhouette == None: - self.get_silhouette() - return self._intercluster_dist - - def _get_silh(self): - if self._silhouette == None: - self.get_silhouette() - return self._silhouette - - def _get_prof(self): - if self._profile is None: - self._calculate_avg_profile() - return self._profile - - def _get_std(self): - if self._std_profile is None: - self._calculate_avg_profile() - return self._std_profile - - def _set_profile(self, value): - self._profile = value - - intracluster_dist = property(fget=_get_intra, fset=_set_forbidden) - intercluster_dist = property(fget=_get_inter, fset=_set_forbidden) - silhouette = property(fget=_get_silh, fset=_set_forbidden) - profile = property(fget=_get_prof, fset=_set_profile) - deviation = property(fget=_get_std, fset=_set_forbidden) - - def __init__(self, newick = None, text_array = None, \ - fdist=clustvalidation.default_dist): - # Default dist is spearman_dist when scipy module is loaded - # otherwise, it is set to euclidean_dist. - - # Initialize basic tree features and loads the newick (if any) - TreeNode.__init__(self, newick) - self._fdist = None - self._silhouette = None - self._intercluster_dist = None - self._intracluster_dist = None - self._profile = None - self._std_profile = None - - # Cluster especific features - self.features.add("intercluster_dist") - self.features.add("intracluster_dist") - self.features.add("silhouette") - self.features.add("profile") - self.features.add("deviation") - - # Initialize tree with array data - if text_array: - self.link_to_arraytable(text_array) - - if newick: - self.set_distance_function(fdist) - - def __repr__(self): - return "ClusterTree node (%s)" %hex(self.__hash__()) - - def set_distance_function(self, fn): - """ Sets the distance function used to calculate cluster - distances and silouette index. - - ARGUMENTS: - - fn: a pointer to python function acepting two arrays (numpy) as - arguments. - - EXAMPLE: - - # A simple euclidean distance - my_dist_fn = lambda x,y: abs(x-y) - tree.set_distance_function(my_dist_fn) - - """ - for n in self.traverse(): - n._fdist = fn - n._silhouette = None - n._intercluster_dist = None - n._intracluster_dist = None - - def link_to_arraytable(self, arraytbl): - """ Allows to link a given arraytable object to the tree - structure under this node. Row names in the arraytable object - are expected to match leaf names. - - Returns a list of nodes for with profiles could not been found - in arraytable. - - """ - - # Initialize tree with array data - - if type(arraytbl) == ArrayTable: - array = arraytbl - else: - array = ArrayTable(arraytbl) - - missing_leaves = [] - matrix_values = [i for r in xrange(len(array.matrix))\ - for i in array.matrix[r] if numpy.isfinite(i)] - - array._matrix_min = min(matrix_values) - array._matrix_max = max(matrix_values) - - for n in self.traverse(): - n.arraytable = array - if n.is_leaf() and n.name in array.rowNames: - n._profile = array.get_row_vector(n.name) - elif n.is_leaf(): - n._profile = [NaN]*len(array.colNames) - missing_leaves.append(n) - - - if len(missing_leaves)>0: - print >>stderr, \ - """[%d] leaf names could not be mapped to the matrix rows.""" %\ - len(missing_leaves) - - self.arraytable = array - - def iter_leaf_profiles(self): - """ Returns an iterator over all the profiles associated to - the leaves under this node.""" - for l in self.iter_leaves(): - yield l.get_profile()[0] - - def get_leaf_profiles(self): - """ Returns the list of all the profiles associated to the - leaves under this node.""" - return [l.get_profile()[0] for l in self.iter_leaves()] - - def get_silhouette(self, fdist=None): - """ Calculates the node's silhouette value by using a given - distance function. By default, euclidean distance is used. It - also calculates the deviation profile, mean profile, and - inter/intra-cluster distances. - - It sets the following features into the analyzed node: - - node.intracluster - - node.intercluster - - node.silhouete - - intracluster distances a(i) are calculated as the Centroid - Diameter - - intercluster distances b(i) are calculated as the Centroid linkage distance - - ** Rousseeuw, P.J. (1987) Silhouettes: A graphical aid to the - interpretation and validation of cluster analysis. - J. Comput. Appl. Math., 20, 53-65. - - """ - if fdist is None: - fdist = self._fdist - - # Updates internal values - self._silhouette, self._intracluster_dist, self._intercluster_dist = \ - clustvalidation.get_silhouette_width(fdist, self) - # And returns them - return self._silhouette, self._intracluster_dist, self._intercluster_dist - - def get_dunn(self, clusters, fdist=None): - """ Calculates the Dunn index for the given set of descendant - nodes. - """ - - if fdist is None: - fdist = self._fdist - nodes = _translate_nodes(self, *clusters) - return clustvalidation.get_dunn_index(fdist, *nodes) - - def _calculate_avg_profile(self): - """ This internal function updates the mean profile - associated to an internal node. """ - - # Updates internal values - self._profile, self._std_profile = clustvalidation.get_avg_profile(self) - - -# cosmetic alias -#: .. currentmodule:: ete2 -# -ClusterTree = ClusterNode diff --git a/ete2/clustering/clustertree.pyc b/ete2/clustering/clustertree.pyc deleted file mode 100644 index 671a5b9..0000000 Binary files a/ete2/clustering/clustertree.pyc and /dev/null differ diff --git a/ete2/clustering/clustvalidation.py b/ete2/clustering/clustvalidation.py deleted file mode 100644 index 3632457..0000000 --- a/ete2/clustering/clustvalidation.py +++ /dev/null @@ -1,204 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -import numpy -from math import sqrt - -def safe_mean(values): - """ Returns mean value discarding non finite values """ - valid_values = [] - for v in values: - if numpy.isfinite(v): - valid_values.append(v) - return numpy.mean(valid_values), numpy.std(valid_values) - -def safe_mean_vector(vectors): - """ Returns mean profile discarding non finite values. - """ - # if only one vector, avg = itself - if len(vectors)==1: - return vectors[0], numpy.zeros(len(vectors[0])) - # Takes the vector length form the first item - length = len(vectors[0]) - - safe_mean = [] - safe_std = [] - - for pos in xrange(length): - pos_mean = [] - for v in vectors: - if numpy.isfinite(v[pos]): - pos_mean.append(v[pos]) - safe_mean.append(numpy.mean(pos_mean)) - safe_std.append(numpy.std(pos_mean)) - return numpy.array(safe_mean), numpy.array(safe_std) - -def get_silhouette_width(fdist, cluster): - sisters = cluster.get_sisters() - - # Calculates silhouette - silhouette = [] - intra_dist = [] - inter_dist = [] - for st in sisters: - if st.profile is None: - continue - for i in cluster.iter_leaves(): - # Skip nodes without profile - if i._profile is not None: - # item intraclsuterdist -> Centroid Diameter - a = fdist(i.profile, cluster.profile)*2 - # intracluster dist -> Centroid Linkage - b = fdist(i.profile, st.profile) - - if (b-a) == 0.0: - s = 0.0 - else: - s = (b-a) / max(a,b) - - intra_dist.append(a) - inter_dist.append(b) - silhouette.append(s) - - silhouette, std = safe_mean(silhouette) - intracluster_dist, std = safe_mean(intra_dist) - intercluster_dist, std = safe_mean(inter_dist) - return silhouette, intracluster_dist, intercluster_dist - -def get_avg_profile(node): - """ This internal function updates the mean profile - associated to an internal node. """ - - if not node.is_leaf(): - leaf_vectors = [n._profile for n in node.get_leaves() \ - if n._profile is not None] - if len(leaf_vectors)>0: - node._profile, node._std_profile = safe_mean_vector(leaf_vectors) - else: - node._profile, node._std_profile = None, None - return node._profile, node._std_profile - else: - node._std_profile = [0.0]*len(node._profile) - return node._profile, [0.0]*len(node._profile) - - -def get_dunn_index(fdist, *clusters): - """ - Returns the Dunn index for the given selection of nodes. - - J.C. Dunn. Well separated clusters and optimal fuzzy - partitions. 1974. J.Cybern. 4. 95-104. - - """ - - if len(clusters)<2: - raise ValueError, "At least 2 clusters are required" - - intra_dist = [] - for c in clusters: - for i in c.get_leaves(): - if i is not None: - # item intraclsuterdist -> Centroid Diameter - a = fdist(i.profile, c.profile)*2 - intra_dist.append(a) - max_a = numpy.max(intra_dist) - inter_dist = [] - for i, ci in enumerate(clusters): - for cj in clusters[i+1:]: - # intracluster dist -> Centroid Linkage - b = fdist(ci.profile, cj.profile) - inter_dist.append(b) - min_b = numpy.min(inter_dist) - - if max_a == 0.0: - D = 0.0 - else: - D = min_b / max_a - return D - - - -# #################### -# distance functions -# #################### - -def pearson_dist(v1, v2): - if (v1 == v2).all(): - return 0.0 - else: - return 1.0 - stats.pearsonr(list(v1),list(v2))[0] - -def spearman_dist(v1, v2): - if (v1 == v2).all(): - return 0.0 - else: - return 1.0 - stats.spearmanr(list(v1),list(v2))[0] - -def euclidean_dist(v1,v2): - if (v1 == v2).all(): - return 0.0 - else: - return sqrt( square_euclidean_dist(v1,v2) ) - -def square_euclidean_dist(v1,v2): - if (v1 == v2).all(): - return 0.0 - valids = 0 - distance= 0.0 - for i in xrange(len(v1)): - if numpy.isfinite(v1[i]) and numpy.isfinite(v2[i]): - valids += 1 - d = v1[i]-v2[i] - distance += d*d - if valids==0: - raise ValueError, "Cannot calculate values" - return distance/valids - -try: - from scipy import stats -except ImportError: - try: - import stats - default_dist = spearman_dist - except ImportError: - default_dist = euclidean_dist -else: - default_dist = spearman_dist diff --git a/ete2/clustering/clustvalidation.pyc b/ete2/clustering/clustvalidation.pyc deleted file mode 100644 index f40131b..0000000 Binary files a/ete2/clustering/clustvalidation.pyc and /dev/null differ diff --git a/ete2/clustering/pstat.py b/ete2/clustering/pstat.py deleted file mode 100644 index 7393bdc..0000000 --- a/ete2/clustering/pstat.py +++ /dev/null @@ -1,1108 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - - -# Copyright (c) 1999-2007 Gary Strangman; All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# Comments and/or additions are welcome (send e-mail to: -# strang@nmr.mgh.harvard.edu). -# -""" -pstat.py module - -################################################# -####### Written by: Gary Strangman ########### -####### Last modified: Dec 18, 2007 ########### -################################################# - -This module provides some useful list and array manipulation routines -modeled after those found in the |Stat package by Gary Perlman, plus a -number of other useful list/file manipulation functions. The list-based -functions include: - - abut (source,*args) - simpleabut (source, addon) - colex (listoflists,cnums) - collapse (listoflists,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None) - dm (listoflists,criterion) - flat (l) - linexand (listoflists,columnlist,valuelist) - linexor (listoflists,columnlist,valuelist) - linedelimited (inlist,delimiter) - lineincols (inlist,colsize) - lineincustcols (inlist,colsizes) - list2string (inlist) - makelol(inlist) - makestr(x) - printcc (lst,extra=2) - printincols (listoflists,colsize) - pl (listoflists) - printl(listoflists) - replace (lst,oldval,newval) - recode (inlist,listmap,cols='all') - remap (listoflists,criterion) - roundlist (inlist,num_digits_to_round_floats_to) - sortby(listoflists,sortcols) - unique (inlist) - duplicates(inlist) - writedelimited (listoflists, delimiter, file, writetype='w') - -Some of these functions have alternate versions which are defined only if -Numeric (NumPy) can be imported. These functions are generally named as -above, with an 'a' prefix. - - aabut (source, *args) - acolex (a,indices,axis=1) - acollapse (a,keepcols,collapsecols,sterr=0,ns=0) - adm (a,criterion) - alinexand (a,columnlist,valuelist) - alinexor (a,columnlist,valuelist) - areplace (a,oldval,newval) - arecode (a,listmap,col='all') - arowcompare (row1, row2) - arowsame (row1, row2) - asortrows(a,axis=0) - aunique(inarray) - aduplicates(inarray) - -Currently, the code is all but completely un-optimized. In many cases, the -array versions of functions amount simply to aliases to built-in array -functions/methods. Their inclusion here is for function name consistency. -""" - -## CHANGE LOG: -## ========== -## 07-11-26 ... edited to work with numpy -## 01-11-15 ... changed list2string() to accept a delimiter -## 01-06-29 ... converted exec()'s to eval()'s to make compatible with Py2.1 -## 01-05-31 ... added duplicates() and aduplicates() functions -## 00-12-28 ... license made GPL, docstring and import requirements -## 99-11-01 ... changed version to 0.3 -## 99-08-30 ... removed get, getstrings, put, aget, aput (into io.py) -## 03/27/99 ... added areplace function, made replace fcn recursive -## 12/31/98 ... added writefc function for ouput to fixed column sizes -## 12/07/98 ... fixed import problem (failed on collapse() fcn) -## added __version__ variable (now 0.2) -## 12/05/98 ... updated doc-strings -## added features to collapse() function -## added flat() function for lists -## fixed a broken asortrows() -## 11/16/98 ... fixed minor bug in aput for 1D arrays -## -## 11/08/98 ... fixed aput to output large arrays correctly - -import stats # required 3rd party module -import string, copy -from types import * - -__version__ = 0.4 - -###=========================== LIST FUNCTIONS ========================== -### -### Here are the list functions, DEFINED FOR ALL SYSTEMS. -### Array functions (for NumPy-enabled computers) appear below. -### - -def abut (source,*args): - """ -Like the |Stat abut command. It concatenates two lists side-by-side -and returns the result. '2D' lists are also accomodated for either argument -(source or addon). CAUTION: If one list is shorter, it will be repeated -until it is as long as the longest list. If this behavior is not desired, -use pstat.simpleabut(). - -Usage: abut(source, args) where args=any # of lists -Returns: a list of lists as long as the LONGEST list past, source on the - 'left', lists in attached consecutively on the 'right' -""" - - if type(source) not in [ListType,TupleType]: - source = [source] - for addon in args: - if type(addon) not in [ListType,TupleType]: - addon = [addon] - if len(addon) < len(source): # is source list longer? - if len(source) % len(addon) == 0: # are they integer multiples? - repeats = len(source)/len(addon) # repeat addon n times - origadd = copy.deepcopy(addon) - for i in range(repeats-1): - addon = addon + origadd - else: - repeats = len(source)/len(addon)+1 # repeat addon x times, - origadd = copy.deepcopy(addon) # x is NOT an integer - for i in range(repeats-1): - addon = addon + origadd - addon = addon[0:len(source)] - elif len(source) < len(addon): # is addon list longer? - if len(addon) % len(source) == 0: # are they integer multiples? - repeats = len(addon)/len(source) # repeat source n times - origsour = copy.deepcopy(source) - for i in range(repeats-1): - source = source + origsour - else: - repeats = len(addon)/len(source)+1 # repeat source x times, - origsour = copy.deepcopy(source) # x is NOT an integer - for i in range(repeats-1): - source = source + origsour - source = source[0:len(addon)] - - source = simpleabut(source,addon) - return source - - -def simpleabut (source, addon): - """ -Concatenates two lists as columns and returns the result. '2D' lists -are also accomodated for either argument (source or addon). This DOES NOT -repeat either list to make the 2 lists of equal length. Beware of list pairs -with different lengths ... the resulting list will be the length of the -FIRST list passed. - -Usage: simpleabut(source,addon) where source, addon=list (or list-of-lists) -Returns: a list of lists as long as source, with source on the 'left' and - addon on the 'right' -""" - if type(source) not in [ListType,TupleType]: - source = [source] - if type(addon) not in [ListType,TupleType]: - addon = [addon] - minlen = min(len(source),len(addon)) - list = copy.deepcopy(source) # start abut process - if type(source[0]) not in [ListType,TupleType]: - if type(addon[0]) not in [ListType,TupleType]: - for i in range(minlen): - list[i] = [source[i]] + [addon[i]] # source/addon = column - else: - for i in range(minlen): - list[i] = [source[i]] + addon[i] # addon=list-of-lists - else: - if type(addon[0]) not in [ListType,TupleType]: - for i in range(minlen): - list[i] = source[i] + [addon[i]] # source=list-of-lists - else: - for i in range(minlen): - list[i] = source[i] + addon[i] # source/addon = list-of-lists - source = list - return source - - -def colex (listoflists,cnums): - """ -Extracts from listoflists the columns specified in the list 'cnums' -(cnums can be an integer, a sequence of integers, or a string-expression that -corresponds to a slice operation on the variable x ... e.g., 'x[3:]' will colex -columns 3 onward from the listoflists). - -Usage: colex (listoflists,cnums) -Returns: a list-of-lists corresponding to the columns from listoflists - specified by cnums, in the order the column numbers appear in cnums -""" - global index - column = 0 - if type(cnums) in [ListType,TupleType]: # if multiple columns to get - index = cnums[0] - column = map(lambda x: x[index], listoflists) - for col in cnums[1:]: - index = col - column = abut(column,map(lambda x: x[index], listoflists)) - elif type(cnums) == StringType: # if an 'x[3:]' type expr. - evalstring = 'map(lambda x: x'+cnums+', listoflists)' - column = eval(evalstring) - else: # else it's just 1 col to get - index = cnums - column = map(lambda x: x[index], listoflists) - return column - - -def collapse (listoflists,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None): - """ -Averages data in collapsecol, keeping all unique items in keepcols -(using unique, which keeps unique LISTS of column numbers), retaining the -unique sets of values in keepcols, the mean for each. Setting fcn1 -and/or fcn2 to point to a function rather than None (e.g., stats.sterr, len) -will append those results (e.g., the sterr, N) after each calculated mean. -cfcn is the collapse function to apply (defaults to mean, defined here in the -pstat module to avoid circular imports with stats.py, but harmonicmean or -others could be passed). - -Usage: collapse (listoflists,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None) -Returns: a list of lists with all unique permutations of entries appearing in - columns ("conditions") specified by keepcols, abutted with the result of - cfcn (if cfcn=None, defaults to the mean) of each column specified by - collapsecols. -""" - def collmean (inlist): - s = 0 - for item in inlist: - s = s + item - return s/float(len(inlist)) - - if type(keepcols) not in [ListType,TupleType]: - keepcols = [keepcols] - if type(collapsecols) not in [ListType,TupleType]: - collapsecols = [collapsecols] - if cfcn == None: - cfcn = collmean - if keepcols == []: - means = [0]*len(collapsecols) - for i in range(len(collapsecols)): - avgcol = colex(listoflists,collapsecols[i]) - means[i] = cfcn(avgcol) - if fcn1: - try: - test = fcn1(avgcol) - except: - test = 'N/A' - means[i] = [means[i], test] - if fcn2: - try: - test = fcn2(avgcol) - except: - test = 'N/A' - try: - means[i] = means[i] + [len(avgcol)] - except TypeError: - means[i] = [means[i],len(avgcol)] - return means - else: - values = colex(listoflists,keepcols) - uniques = unique(values) - uniques.sort() - newlist = [] - if type(keepcols) not in [ListType,TupleType]: keepcols = [keepcols] - for item in uniques: - if type(item) not in [ListType,TupleType]: item =[item] - tmprows = linexand(listoflists,keepcols,item) - for col in collapsecols: - avgcol = colex(tmprows,col) - item.append(cfcn(avgcol)) - if fcn1 <> None: - try: - test = fcn1(avgcol) - except: - test = 'N/A' - item.append(test) - if fcn2 <> None: - try: - test = fcn2(avgcol) - except: - test = 'N/A' - item.append(test) - newlist.append(item) - return newlist - - -def dm (listoflists,criterion): - """ -Returns rows from the passed list of lists that meet the criteria in -the passed criterion expression (a string as a function of x; e.g., 'x[3]>=9' -will return all rows where the 4th column>=9 and "x[2]=='N'" will return rows -with column 2 equal to the string 'N'). - -Usage: dm (listoflists, criterion) -Returns: rows from listoflists that meet the specified criterion. -""" - function = 'filter(lambda x: '+criterion+',listoflists)' - lines = eval(function) - return lines - - -def flat(l): - """ -Returns the flattened version of a '2D' list. List-correlate to the a.ravel()() -method of NumPy arrays. - -Usage: flat(l) -""" - newl = [] - for i in range(len(l)): - for j in range(len(l[i])): - newl.append(l[i][j]) - return newl - - -def linexand (listoflists,columnlist,valuelist): - """ -Returns the rows of a list of lists where col (from columnlist) = val -(from valuelist) for EVERY pair of values (columnlist[i],valuelists[i]). -len(columnlist) must equal len(valuelist). - -Usage: linexand (listoflists,columnlist,valuelist) -Returns: the rows of listoflists where columnlist[i]=valuelist[i] for ALL i -""" - if type(columnlist) not in [ListType,TupleType]: - columnlist = [columnlist] - if type(valuelist) not in [ListType,TupleType]: - valuelist = [valuelist] - criterion = '' - for i in range(len(columnlist)): - if type(valuelist[i])==StringType: - critval = '\'' + valuelist[i] + '\'' - else: - critval = str(valuelist[i]) - criterion = criterion + ' x['+str(columnlist[i])+']=='+critval+' and' - criterion = criterion[0:-3] # remove the "and" after the last crit - function = 'filter(lambda x: '+criterion+',listoflists)' - lines = eval(function) - return lines - - -def linexor (listoflists,columnlist,valuelist): - """ -Returns the rows of a list of lists where col (from columnlist) = val -(from valuelist) for ANY pair of values (colunmlist[i],valuelist[i[). -One value is required for each column in columnlist. If only one value -exists for columnlist but multiple values appear in valuelist, the -valuelist values are all assumed to pertain to the same column. - -Usage: linexor (listoflists,columnlist,valuelist) -Returns: the rows of listoflists where columnlist[i]=valuelist[i] for ANY i -""" - if type(columnlist) not in [ListType,TupleType]: - columnlist = [columnlist] - if type(valuelist) not in [ListType,TupleType]: - valuelist = [valuelist] - criterion = '' - if len(columnlist) == 1 and len(valuelist) > 1: - columnlist = columnlist*len(valuelist) - for i in range(len(columnlist)): # build an exec string - if type(valuelist[i])==StringType: - critval = '\'' + valuelist[i] + '\'' - else: - critval = str(valuelist[i]) - criterion = criterion + ' x['+str(columnlist[i])+']=='+critval+' or' - criterion = criterion[0:-2] # remove the "or" after the last crit - function = 'filter(lambda x: '+criterion+',listoflists)' - lines = eval(function) - return lines - - -def linedelimited (inlist,delimiter): - """ -Returns a string composed of elements in inlist, with each element -separated by 'delimiter.' Used by function writedelimited. Use '\t' -for tab-delimiting. - -Usage: linedelimited (inlist,delimiter) -""" - outstr = '' - for item in inlist: - if type(item) <> StringType: - item = str(item) - outstr = outstr + item + delimiter - outstr = outstr[0:-1] - return outstr - - -def lineincols (inlist,colsize): - """ -Returns a string composed of elements in inlist, with each element -right-aligned in columns of (fixed) colsize. - -Usage: lineincols (inlist,colsize) where colsize is an integer -""" - outstr = '' - for item in inlist: - if type(item) <> StringType: - item = str(item) - size = len(item) - if size <= colsize: - for i in range(colsize-size): - outstr = outstr + ' ' - outstr = outstr + item - else: - outstr = outstr + item[0:colsize+1] - return outstr - - -def lineincustcols (inlist,colsizes): - """ -Returns a string composed of elements in inlist, with each element -right-aligned in a column of width specified by a sequence colsizes. The -length of colsizes must be greater than or equal to the number of columns -in inlist. - -Usage: lineincustcols (inlist,colsizes) -Returns: formatted string created from inlist -""" - outstr = '' - for i in range(len(inlist)): - if type(inlist[i]) <> StringType: - item = str(inlist[i]) - else: - item = inlist[i] - size = len(item) - if size <= colsizes[i]: - for j in range(colsizes[i]-size): - outstr = outstr + ' ' - outstr = outstr + item - else: - outstr = outstr + item[0:colsizes[i]+1] - return outstr - - -def list2string (inlist,delimit=' '): - """ -Converts a 1D list to a single long string for file output, using -the string.join function. - -Usage: list2string (inlist,delimit=' ') -Returns: the string created from inlist -""" - stringlist = map(makestr,inlist) - return string.join(stringlist,delimit) - - -def makelol(inlist): - """ -Converts a 1D list to a 2D list (i.e., a list-of-lists). Useful when you -want to use put() to write a 1D list one item per line in the file. - -Usage: makelol(inlist) -Returns: if l = [1,2,'hi'] then returns [[1],[2],['hi']] etc. -""" - x = [] - for item in inlist: - x.append([item]) - return x - - -def makestr (x): - if type(x) <> StringType: - x = str(x) - return x - - -def printcc (lst,extra=2): - """ -Prints a list of lists in columns, customized by the max size of items -within the columns (max size of items in col, plus 'extra' number of spaces). -Use 'dashes' or '\\n' in the list-of-lists to print dashes or blank lines, -respectively. - -Usage: printcc (lst,extra=2) -Returns: None -""" - if type(lst[0]) not in [ListType,TupleType]: - lst = [lst] - rowstokill = [] - list2print = copy.deepcopy(lst) - for i in range(len(lst)): - if lst[i] == ['\n'] or lst[i]=='\n' or lst[i]=='dashes' or lst[i]=='' or lst[i]==['']: - rowstokill = rowstokill + [i] - rowstokill.reverse() # delete blank rows from the end - for row in rowstokill: - del list2print[row] - maxsize = [0]*len(list2print[0]) - for col in range(len(list2print[0])): - items = colex(list2print,col) - items = map(makestr,items) - maxsize[col] = max(map(len,items)) + extra - for row in lst: - if row == ['\n'] or row == '\n' or row == '' or row == ['']: - print - elif row == ['dashes'] or row == 'dashes': - dashes = [0]*len(maxsize) - for j in range(len(maxsize)): - dashes[j] = '-'*(maxsize[j]-2) - print lineincustcols(dashes,maxsize) - else: - print lineincustcols(row,maxsize) - return None - - -def printincols (listoflists,colsize): - """ -Prints a list of lists in columns of (fixed) colsize width, where -colsize is an integer. - -Usage: printincols (listoflists,colsize) -Returns: None -""" - for row in listoflists: - print lineincols(row,colsize) - return None - - -def pl (listoflists): - """ -Prints a list of lists, 1 list (row) at a time. - -Usage: pl(listoflists) -Returns: None -""" - for row in listoflists: - if row[-1] == '\n': - print row, - else: - print row - return None - - -def printl(listoflists): - """Alias for pl.""" - pl(listoflists) - return - - -def replace (inlst,oldval,newval): - """ -Replaces all occurrences of 'oldval' with 'newval', recursively. - -Usage: replace (inlst,oldval,newval) -""" - lst = inlst*1 - for i in range(len(lst)): - if type(lst[i]) not in [ListType,TupleType]: - if lst[i]==oldval: lst[i]=newval - else: - lst[i] = replace(lst[i],oldval,newval) - return lst - - -def recode (inlist,listmap,cols=None): - """ -Changes the values in a list to a new set of values (useful when -you need to recode data from (e.g.) strings to numbers. cols defaults -to None (meaning all columns are recoded). - -Usage: recode (inlist,listmap,cols=None) cols=recode cols, listmap=2D list -Returns: inlist with the appropriate values replaced with new ones -""" - lst = copy.deepcopy(inlist) - if cols != None: - if type(cols) not in [ListType,TupleType]: - cols = [cols] - for col in cols: - for row in range(len(lst)): - try: - idx = colex(listmap,0).index(lst[row][col]) - lst[row][col] = listmap[idx][1] - except ValueError: - pass - else: - for row in range(len(lst)): - for col in range(len(lst)): - try: - idx = colex(listmap,0).index(lst[row][col]) - lst[row][col] = listmap[idx][1] - except ValueError: - pass - return lst - - -def remap (listoflists,criterion): - """ -Remaps values in a given column of a 2D list (listoflists). This requires -a criterion as a function of 'x' so that the result of the following is -returned ... map(lambda x: 'criterion',listoflists). - -Usage: remap(listoflists,criterion) criterion=string -Returns: remapped version of listoflists -""" - function = 'map(lambda x: '+criterion+',listoflists)' - lines = eval(function) - return lines - - -def roundlist (inlist,digits): - """ -Goes through each element in a 1D or 2D inlist, and applies the following -function to all elements of FloatType ... round(element,digits). - -Usage: roundlist(inlist,digits) -Returns: list with rounded floats -""" - if type(inlist[0]) in [IntType, FloatType]: - inlist = [inlist] - l = inlist*1 - for i in range(len(l)): - for j in range(len(l[i])): - if type(l[i][j])==FloatType: - l[i][j] = round(l[i][j],digits) - return l - - -def sortby(listoflists,sortcols): - """ -Sorts a list of lists on the column(s) specified in the sequence -sortcols. - -Usage: sortby(listoflists,sortcols) -Returns: sorted list, unchanged column ordering -""" - newlist = abut(colex(listoflists,sortcols),listoflists) - newlist.sort() - try: - numcols = len(sortcols) - except TypeError: - numcols = 1 - crit = '[' + str(numcols) + ':]' - newlist = colex(newlist,crit) - return newlist - - -def unique (inlist): - """ -Returns all unique items in the passed list. If the a list-of-lists -is passed, unique LISTS are found (i.e., items in the first dimension are -compared). - -Usage: unique (inlist) -Returns: the unique elements (or rows) in inlist -""" - uniques = [] - for item in inlist: - if item not in uniques: - uniques.append(item) - return uniques - -def duplicates(inlist): - """ -Returns duplicate items in the FIRST dimension of the passed list. - -Usage: duplicates (inlist) -""" - dups = [] - for i in range(len(inlist)): - if inlist[i] in inlist[i+1:]: - dups.append(inlist[i]) - return dups - - -def nonrepeats(inlist): - """ -Returns items that are NOT duplicated in the first dim of the passed list. - -Usage: nonrepeats (inlist) -""" - nonrepeats = [] - for i in range(len(inlist)): - if inlist.count(inlist[i]) == 1: - nonrepeats.append(inlist[i]) - return nonrepeats - - -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== -#=================== PSTAT ARRAY FUNCTIONS ===================== - -try: # DEFINE THESE *ONLY* IF numpy IS AVAILABLE - import numpy as N - - def aabut (source, *args): - """ -Like the |Stat abut command. It concatenates two arrays column-wise -and returns the result. CAUTION: If one array is shorter, it will be -repeated until it is as long as the other. - -Usage: aabut (source, args) where args=any # of arrays -Returns: an array as long as the LONGEST array past, source appearing on the - 'left', arrays in attached on the 'right'. -""" - if len(source.shape)==1: - width = 1 - source = N.resize(source,[source.shape[0],width]) - else: - width = source.shape[1] - for addon in args: - if len(addon.shape)==1: - width = 1 - addon = N.resize(addon,[source.shape[0],width]) - else: - width = source.shape[1] - if len(addon) < len(source): - addon = N.resize(addon,[source.shape[0],addon.shape[1]]) - elif len(source) < len(addon): - source = N.resize(source,[addon.shape[0],source.shape[1]]) - source = N.concatenate((source,addon),1) - return source - - - def acolex (a,indices,axis=1): - """ -Extracts specified indices (a list) from passed array, along passed -axis (column extraction is default). BEWARE: A 1D array is presumed to be a -column-array (and that the whole array will be returned as a column). - -Usage: acolex (a,indices,axis=1) -Returns: the columns of a specified by indices -""" - if type(indices) not in [ListType,TupleType,N.ndarray]: - indices = [indices] - if len(N.shape(a)) == 1: - cols = N.resize(a,[a.shape[0],1]) - else: - cols = N.take(a,indices,axis) - return cols - - - def acollapse (a,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None): - """ -Averages data in collapsecol, keeping all unique items in keepcols -(using unique, which keeps unique LISTS of column numbers), retaining -the unique sets of values in keepcols, the mean for each. If stderror or -N of the mean are desired, set either or both parameters to 1. - -Usage: acollapse (a,keepcols,collapsecols,fcn1=None,fcn2=None,cfcn=None) -Returns: unique 'conditions' specified by the contents of columns specified - by keepcols, abutted with the mean(s) of column(s) specified by - collapsecols -""" - def acollmean (inarray): - return N.sum(N.ravel(inarray)) - - if type(keepcols) not in [ListType,TupleType,N.ndarray]: - keepcols = [keepcols] - if type(collapsecols) not in [ListType,TupleType,N.ndarray]: - collapsecols = [collapsecols] - - if cfcn == None: - cfcn = acollmean - if keepcols == []: - avgcol = acolex(a,collapsecols) - means = N.sum(avgcol)/float(len(avgcol)) - if fcn1<>None: - try: - test = fcn1(avgcol) - except: - test = N.array(['N/A']*len(means)) - means = aabut(means,test) - if fcn2<>None: - try: - test = fcn2(avgcol) - except: - test = N.array(['N/A']*len(means)) - means = aabut(means,test) - return means - else: - if type(keepcols) not in [ListType,TupleType,N.ndarray]: - keepcols = [keepcols] - values = colex(a,keepcols) # so that "item" can be appended (below) - uniques = unique(values) # get a LIST, so .sort keeps rows intact - uniques.sort() - newlist = [] - for item in uniques: - if type(item) not in [ListType,TupleType,N.ndarray]: - item =[item] - tmprows = alinexand(a,keepcols,item) - for col in collapsecols: - avgcol = acolex(tmprows,col) - item.append(acollmean(avgcol)) - if fcn1<>None: - try: - test = fcn1(avgcol) - except: - test = 'N/A' - item.append(test) - if fcn2<>None: - try: - test = fcn2(avgcol) - except: - test = 'N/A' - item.append(test) - newlist.append(item) - try: - new_a = N.array(newlist) - except TypeError: - new_a = N.array(newlist,'O') - return new_a - - - def adm (a,criterion): - """ -Returns rows from the passed list of lists that meet the criteria in -the passed criterion expression (a string as a function of x). - -Usage: adm (a,criterion) where criterion is like 'x[2]==37' -""" - function = 'filter(lambda x: '+criterion+',a)' - lines = eval(function) - try: - lines = N.array(lines) - except: - lines = N.array(lines,dtype='O') - return lines - - - def isstring(x): - if type(x)==StringType: - return 1 - else: - return 0 - - - def alinexand (a,columnlist,valuelist): - """ -Returns the rows of an array where col (from columnlist) = val -(from valuelist). One value is required for each column in columnlist. - -Usage: alinexand (a,columnlist,valuelist) -Returns: the rows of a where columnlist[i]=valuelist[i] for ALL i -""" - if type(columnlist) not in [ListType,TupleType,N.ndarray]: - columnlist = [columnlist] - if type(valuelist) not in [ListType,TupleType,N.ndarray]: - valuelist = [valuelist] - criterion = '' - for i in range(len(columnlist)): - if type(valuelist[i])==StringType: - critval = '\'' + valuelist[i] + '\'' - else: - critval = str(valuelist[i]) - criterion = criterion + ' x['+str(columnlist[i])+']=='+critval+' and' - criterion = criterion[0:-3] # remove the "and" after the last crit - return adm(a,criterion) - - - def alinexor (a,columnlist,valuelist): - """ -Returns the rows of an array where col (from columnlist) = val (from -valuelist). One value is required for each column in columnlist. -The exception is if either columnlist or valuelist has only 1 value, -in which case that item will be expanded to match the length of the -other list. - -Usage: alinexor (a,columnlist,valuelist) -Returns: the rows of a where columnlist[i]=valuelist[i] for ANY i -""" - if type(columnlist) not in [ListType,TupleType,N.ndarray]: - columnlist = [columnlist] - if type(valuelist) not in [ListType,TupleType,N.ndarray]: - valuelist = [valuelist] - criterion = '' - if len(columnlist) == 1 and len(valuelist) > 1: - columnlist = columnlist*len(valuelist) - elif len(valuelist) == 1 and len(columnlist) > 1: - valuelist = valuelist*len(columnlist) - for i in range(len(columnlist)): - if type(valuelist[i])==StringType: - critval = '\'' + valuelist[i] + '\'' - else: - critval = str(valuelist[i]) - criterion = criterion + ' x['+str(columnlist[i])+']=='+critval+' or' - criterion = criterion[0:-2] # remove the "or" after the last crit - return adm(a,criterion) - - - def areplace (a,oldval,newval): - """ -Replaces all occurrences of oldval with newval in array a. - -Usage: areplace(a,oldval,newval) -""" - return N.where(a==oldval,newval,a) - - - def arecode (a,listmap,col='all'): - """ -Remaps the values in an array to a new set of values (useful when -you need to recode data from (e.g.) strings to numbers as most stats -packages require. Can work on SINGLE columns, or 'all' columns at once. -@@@BROKEN 2007-11-26 - -Usage: arecode (a,listmap,col='all') -Returns: a version of array a where listmap[i][0] = (instead) listmap[i][1] -""" - ashape = a.shape - if col == 'all': - work = a.ravel() - else: - work = acolex(a,col) - work = work.ravel() - for pair in listmap: - if type(pair[1]) == StringType or work.dtype.char=='O' or a.dtype.char=='O': - work = N.array(work,dtype='O') - a = N.array(a,dtype='O') - for i in range(len(work)): - if work[i]==pair[0]: - work[i] = pair[1] - if col == 'all': - return N.reshape(work,ashape) - else: - return N.concatenate([a[:,0:col],work[:,N.newaxis],a[:,col+1:]],1) - else: # must be a non-Object type array and replacement - work = N.where(work==pair[0],pair[1],work) - return N.concatenate([a[:,0:col],work[:,N.newaxis],a[:,col+1:]],1) - - - def arowcompare(row1, row2): - """ -Compares two rows from an array, regardless of whether it is an -array of numbers or of python objects (which requires the cmp function). -@@@PURPOSE? 2007-11-26 - -Usage: arowcompare(row1,row2) -Returns: an array of equal length containing 1s where the two rows had - identical elements and 0 otherwise -""" - return - if row1.dtype.char=='O' or row2.dtype=='O': - cmpvect = N.logical_not(abs(N.array(map(cmp,row1,row2)))) # cmp fcn gives -1,0,1 - else: - cmpvect = N.equal(row1,row2) - return cmpvect - - - def arowsame(row1, row2): - """ -Compares two rows from an array, regardless of whether it is an -array of numbers or of python objects (which requires the cmp function). - -Usage: arowsame(row1,row2) -Returns: 1 if the two rows are identical, 0 otherwise. -""" - cmpval = N.alltrue(arowcompare(row1,row2)) - return cmpval - - - def asortrows(a,axis=0): - """ -Sorts an array "by rows". This differs from the Numeric.sort() function, -which sorts elements WITHIN the given axis. Instead, this function keeps -the elements along the given axis intact, but shifts them 'up or down' -relative to one another. - -Usage: asortrows(a,axis=0) -Returns: sorted version of a -""" - return N.sort(a,axis=axis,kind='mergesort') - - - def aunique(inarray): - """ -Returns unique items in the FIRST dimension of the passed array. Only -works on arrays NOT including string items. - -Usage: aunique (inarray) -""" - uniques = N.array([inarray[0]]) - if len(uniques.shape) == 1: # IF IT'S A 1D ARRAY - for item in inarray[1:]: - if N.add.reduce(N.equal(uniques,item).ravel()) == 0: - try: - uniques = N.concatenate([uniques,N.array[N.newaxis,:]]) - except TypeError: - uniques = N.concatenate([uniques,N.array([item])]) - else: # IT MUST BE A 2+D ARRAY - if inarray.dtype.char != 'O': # not an Object array - for item in inarray[1:]: - if not N.sum(N.alltrue(N.equal(uniques,item),1)): - try: - uniques = N.concatenate( [uniques,item[N.newaxis,:]] ) - except TypeError: # the item to add isn't a list - uniques = N.concatenate([uniques,N.array([item])]) - else: - pass # this item is already in the uniques array - else: # must be an Object array, alltrue/equal functions don't work - for item in inarray[1:]: - newflag = 1 - for unq in uniques: # NOTE: cmp --> 0=same, -1=<, 1=> - test = N.sum(abs(N.array(map(cmp,item,unq)))) - if test == 0: # if item identical to any 1 row in uniques - newflag = 0 # then not a novel item to add - break - if newflag == 1: - try: - uniques = N.concatenate( [uniques,item[N.newaxis,:]] ) - except TypeError: # the item to add isn't a list - uniques = N.concatenate([uniques,N.array([item])]) - return uniques - - - def aduplicates(inarray): - """ -Returns duplicate items in the FIRST dimension of the passed array. Only -works on arrays NOT including string items. - -Usage: aunique (inarray) -""" - inarray = N.array(inarray) - if len(inarray.shape) == 1: # IF IT'S A 1D ARRAY - dups = [] - inarray = inarray.tolist() - for i in range(len(inarray)): - if inarray[i] in inarray[i+1:]: - dups.append(inarray[i]) - dups = aunique(dups) - else: # IT MUST BE A 2+D ARRAY - dups = [] - aslist = inarray.tolist() - for i in range(len(aslist)): - if aslist[i] in aslist[i+1:]: - dups.append(aslist[i]) - dups = unique(dups) - dups = N.array(dups) - return dups - -except ImportError: # IF NUMERIC ISN'T AVAILABLE, SKIP ALL arrayfuncs - pass diff --git a/ete2/clustering/stats.py b/ete2/clustering/stats.py deleted file mode 100644 index 6b3c2f8..0000000 --- a/ete2/clustering/stats.py +++ /dev/null @@ -1,4564 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - - -# Copyright (c) 1999-2007 Gary Strangman; All Rights Reserved. -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -# Comments and/or additions are welcome (send e-mail to: -# strang@nmr.mgh.harvard.edu). -# -""" -stats.py module - -(Requires pstat.py module.) - -################################################# -####### Written by: Gary Strangman ########### -####### Last modified: Dec 18, 2007 ########### -################################################# - -A collection of basic statistical functions for python. The function -names appear below. - -IMPORTANT: There are really *3* sets of functions. The first set has an 'l' -prefix, which can be used with list or tuple arguments. The second set has -an 'a' prefix, which can accept NumPy array arguments. These latter -functions are defined only when NumPy is available on the system. The third -type has NO prefix (i.e., has the name that appears below). Functions of -this set are members of a "Dispatch" class, c/o David Ascher. This class -allows different functions to be called depending on the type of the passed -arguments. Thus, stats.mean is a member of the Dispatch class and -stats.mean(range(20)) will call stats.lmean(range(20)) while -stats.mean(Numeric.arange(20)) will call stats.amean(Numeric.arange(20)). -This is a handy way to keep consistent function names when different -argument types require different functions to be called. Having -implementated the Dispatch class, however, means that to get info on -a given function, you must use the REAL function name ... that is -"print stats.lmean.__doc__" or "print stats.amean.__doc__" work fine, -while "print stats.mean.__doc__" will print the doc for the Dispatch -class. NUMPY FUNCTIONS ('a' prefix) generally have more argument options -but should otherwise be consistent with the corresponding list functions. - -Disclaimers: The function list is obviously incomplete and, worse, the -functions are not optimized. All functions have been tested (some more -so than others), but they are far from bulletproof. Thus, as with any -free software, no warranty or guarantee is expressed or implied. :-) A -few extra functions that don't appear in the list below can be found by -interested treasure-hunters. These functions don't necessarily have -both list and array versions but were deemed useful - -CENTRAL TENDENCY: geometricmean - harmonicmean - mean - median - medianscore - mode - -MOMENTS: moment - variation - skew - kurtosis - skewtest (for Numpy arrays only) - kurtosistest (for Numpy arrays only) - normaltest (for Numpy arrays only) - -ALTERED VERSIONS: tmean (for Numpy arrays only) - tvar (for Numpy arrays only) - tmin (for Numpy arrays only) - tmax (for Numpy arrays only) - tstdev (for Numpy arrays only) - tsem (for Numpy arrays only) - describe - -FREQUENCY STATS: itemfreq - scoreatpercentile - percentileofscore - histogram - cumfreq - relfreq - -VARIABILITY: obrientransform - samplevar - samplestdev - signaltonoise (for Numpy arrays only) - var - stdev - sterr - sem - z - zs - zmap (for Numpy arrays only) - -TRIMMING FCNS: threshold (for Numpy arrays only) - trimboth - trim1 - round (round all vals to 'n' decimals; Numpy only) - -CORRELATION FCNS: covariance (for Numpy arrays only) - correlation (for Numpy arrays only) - paired - pearsonr - spearmanr - pointbiserialr - kendalltau - linregress - -INFERENTIAL STATS: ttest_1samp - ttest_ind - ttest_rel - chisquare - ks_2samp - mannwhitneyu - ranksums - wilcoxont - kruskalwallish - friedmanchisquare - -PROBABILITY CALCS: chisqprob - erfcc - zprob - ksprob - fprob - betacf - gammln - betai - -ANOVA FUNCTIONS: F_oneway - F_value - -SUPPORT FUNCTIONS: writecc - incr - sign (for Numpy arrays only) - sum - cumsum - ss - summult - sumdiffsquared - square_of_sums - shellsort - rankdata - outputpairedstats - findwithin -""" -## CHANGE LOG: -## =========== -## 07-11.26 ... conversion for numpy started -## 07-05-16 ... added Lin's Concordance Correlation Coefficient (alincc) and acov -## 05-08-21 ... added "Dice's coefficient" -## 04-10-26 ... added ap2t(), an ugly fcn for converting p-vals to T-vals -## 04-04-03 ... added amasslinregress() function to do regression on N-D arrays -## 03-01-03 ... CHANGED VERSION TO 0.6 -## fixed atsem() to properly handle limits=None case -## improved histogram and median functions (estbinwidth) and -## fixed atvar() function (wrong answers for neg numbers?!?) -## 02-11-19 ... fixed attest_ind and attest_rel for div-by-zero Overflows -## 02-05-10 ... fixed lchisqprob indentation (failed when df=even) -## 00-12-28 ... removed aanova() to separate module, fixed licensing to -## match Python License, fixed doc string & imports -## 00-04-13 ... pulled all "global" statements, except from aanova() -## added/fixed lots of documentation, removed io.py dependency -## changed to version 0.5 -## 99-11-13 ... added asign() function -## 99-11-01 ... changed version to 0.4 ... enough incremental changes now -## 99-10-25 ... added acovariance and acorrelation functions -## 99-10-10 ... fixed askew/akurtosis to avoid divide-by-zero errors -## added aglm function (crude, but will be improved) -## 99-10-04 ... upgraded acumsum, ass, asummult, asamplevar, avar, etc. to -## all handle lists of 'dimension's and keepdims -## REMOVED ar0, ar2, ar3, ar4 and replaced them with around -## reinserted fixes for abetai to avoid math overflows -## 99-09-05 ... rewrote achisqprob/aerfcc/aksprob/afprob/abetacf/abetai to -## handle multi-dimensional arrays (whew!) -## 99-08-30 ... fixed l/amoment, l/askew, l/akurtosis per D'Agostino (1990) -## added anormaltest per same reference -## re-wrote azprob to calc arrays of probs all at once -## 99-08-22 ... edited attest_ind printing section so arrays could be rounded -## 99-08-19 ... fixed amean and aharmonicmean for non-error(!) overflow on -## short/byte arrays (mean of #s btw 100-300 = -150??) -## 99-08-09 ... fixed asum so that the None case works for Byte arrays -## 99-08-08 ... fixed 7/3 'improvement' to handle t-calcs on N-D arrays -## 99-07-03 ... improved attest_ind, attest_rel (zero-division errortrap) -## 99-06-24 ... fixed bug(?) in attest_ind (n1=a.shape[0]) -## 04/11/99 ... added asignaltonoise, athreshold functions, changed all -## max/min in array section to N.maximum/N.minimum, -## fixed square_of_sums to prevent integer overflow -## 04/10/99 ... !!! Changed function name ... sumsquared ==> square_of_sums -## 03/18/99 ... Added ar0, ar2, ar3 and ar4 rounding functions -## 02/28/99 ... Fixed aobrientransform to return an array rather than a list -## 01/15/99 ... Essentially ceased updating list-versions of functions (!!!) -## 01/13/99 ... CHANGED TO VERSION 0.3 -## fixed bug in a/lmannwhitneyu p-value calculation -## 12/31/98 ... fixed variable-name bug in ldescribe -## 12/19/98 ... fixed bug in findwithin (fcns needed pstat. prefix) -## 12/16/98 ... changed amedianscore to return float (not array) for 1 score -## 12/14/98 ... added atmin and atmax functions -## removed umath from import line (not needed) -## l/ageometricmean modified to reduce chance of overflows (take -## nth root first, then multiply) -## 12/07/98 ... added __version__variable (now 0.2) -## removed all 'stats.' from anova() fcn -## 12/06/98 ... changed those functions (except shellsort) that altered -## arguments in-place ... cumsum, ranksort, ... -## updated (and fixed some) doc-strings -## 12/01/98 ... added anova() function (requires NumPy) -## incorporated Dispatch class -## 11/12/98 ... added functionality to amean, aharmonicmean, ageometricmean -## added 'asum' function (added functionality to N.add.reduce) -## fixed both moment and amoment (two errors) -## changed name of skewness and askewness to skew and askew -## fixed (a)histogram (which sometimes counted points =len(inlist)/2.0: - cfbin = i - break - LRL = smallest + binsize*cfbin # get lower read limit of that bin - cfbelow = cumhist[cfbin-1] - freq = float(hist[cfbin]) # frequency IN the 50%ile bin - median = LRL + ((len(inlist)/2.0 - cfbelow)/float(freq))*binsize # median formula - return median - - -def lmedianscore (inlist): - """ -Returns the 'middle' score of the passed list. If there is an even -number of scores, the mean of the 2 middle scores is returned. - -Usage: lmedianscore(inlist) -""" - - newlist = copy.deepcopy(inlist) - newlist.sort() - if len(newlist) % 2 == 0: # if even number of scores, average middle 2 - index = len(newlist)/2 # integer division correct - median = float(newlist[index] + newlist[index-1]) /2 - else: - index = len(newlist)/2 # int divsion gives mid value when count from 0 - median = newlist[index] - return median - - -def lmode(inlist): - """ -Returns a list of the modal (most common) score(s) in the passed -list. If there is more than one such score, all are returned. The -bin-count for the mode(s) is also returned. - -Usage: lmode(inlist) -Returns: bin-count for mode(s), a list of modal value(s) -""" - - scores = pstat.unique(inlist) - scores.sort() - freq = [] - for item in scores: - freq.append(inlist.count(item)) - maxfreq = max(freq) - mode = [] - stillmore = 1 - while stillmore: - try: - indx = freq.index(maxfreq) - mode.append(scores[indx]) - del freq[indx] - del scores[indx] - except ValueError: - stillmore=0 - return maxfreq, mode - - -#################################### -############ MOMENTS ############# -#################################### - -def lmoment(inlist,moment=1): - """ -Calculates the nth moment about the mean for a sample (defaults to -the 1st moment). Used to calculate coefficients of skewness and kurtosis. - -Usage: lmoment(inlist,moment=1) -Returns: appropriate moment (r) from ... 1/n * SUM((inlist(i)-mean)**r) -""" - if moment == 1: - return 0.0 - else: - mn = mean(inlist) - n = len(inlist) - s = 0 - for x in inlist: - s = s + (x-mn)**moment - return s/float(n) - - -def lvariation(inlist): - """ -Returns the coefficient of variation, as defined in CRC Standard -Probability and Statistics, p.6. - -Usage: lvariation(inlist) -""" - return 100.0*samplestdev(inlist)/float(mean(inlist)) - - -def lskew(inlist): - """ -Returns the skewness of a distribution, as defined in Numerical -Recipies (alternate defn in CRC Standard Probability and Statistics, p.6.) - -Usage: lskew(inlist) -""" - return moment(inlist,3)/pow(moment(inlist,2),1.5) - - -def lkurtosis(inlist): - """ -Returns the kurtosis of a distribution, as defined in Numerical -Recipies (alternate defn in CRC Standard Probability and Statistics, p.6.) - -Usage: lkurtosis(inlist) -""" - return moment(inlist,4)/pow(moment(inlist,2),2.0) - - -def ldescribe(inlist): - """ -Returns some descriptive statistics of the passed list (assumed to be 1D). - -Usage: ldescribe(inlist) -Returns: n, mean, standard deviation, skew, kurtosis -""" - n = len(inlist) - mm = (min(inlist),max(inlist)) - m = mean(inlist) - sd = stdev(inlist) - sk = skew(inlist) - kurt = kurtosis(inlist) - return n, mm, m, sd, sk, kurt - - -#################################### -####### FREQUENCY STATS ########## -#################################### - -def litemfreq(inlist): - """ -Returns a list of pairs. Each pair consists of one of the scores in inlist -and it's frequency count. Assumes a 1D list is passed. - -Usage: litemfreq(inlist) -Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies) -""" - scores = pstat.unique(inlist) - scores.sort() - freq = [] - for item in scores: - freq.append(inlist.count(item)) - return pstat.abut(scores, freq) - - -def lscoreatpercentile (inlist, percent): - """ -Returns the score at a given percentile relative to the distribution -given by inlist. - -Usage: lscoreatpercentile(inlist,percent) -""" - if percent > 1: - print "\nDividing percent>1 by 100 in lscoreatpercentile().\n" - percent = percent / 100.0 - targetcf = percent*len(inlist) - h, lrl, binsize, extras = histogram(inlist) - cumhist = cumsum(copy.deepcopy(h)) - for i in range(len(cumhist)): - if cumhist[i] >= targetcf: - break - score = binsize * ((targetcf - cumhist[i-1]) / float(h[i])) + (lrl+binsize*i) - return score - - -def lpercentileofscore (inlist, score,histbins=10,defaultlimits=None): - """ -Returns the percentile value of a score relative to the distribution -given by inlist. Formula depends on the values used to histogram the data(!). - -Usage: lpercentileofscore(inlist,score,histbins=10,defaultlimits=None) -""" - - h, lrl, binsize, extras = histogram(inlist,histbins,defaultlimits) - cumhist = cumsum(copy.deepcopy(h)) - i = int((score - lrl)/float(binsize)) - pct = (cumhist[i-1]+((score-(lrl+binsize*i))/float(binsize))*h[i])/float(len(inlist)) * 100 - return pct - - -def lhistogram (inlist,numbins=10,defaultreallimits=None,printextras=0): - """ -Returns (i) a list of histogram bin counts, (ii) the smallest value -of the histogram binning, and (iii) the bin width (the last 2 are not -necessarily integers). Default number of bins is 10. If no sequence object -is given for defaultreallimits, the routine picks (usually non-pretty) bins -spanning all the numbers in the inlist. - -Usage: lhistogram (inlist, numbins=10, defaultreallimits=None,suppressoutput=0) -Returns: list of bin values, lowerreallimit, binsize, extrapoints -""" - if (defaultreallimits <> None): - if type(defaultreallimits) not in [ListType,TupleType] or len(defaultreallimits)==1: # only one limit given, assumed to be lower one & upper is calc'd - lowerreallimit = defaultreallimits - upperreallimit = 1.000001 * max(inlist) - else: # assume both limits given - lowerreallimit = defaultreallimits[0] - upperreallimit = defaultreallimits[1] - binsize = (upperreallimit-lowerreallimit)/float(numbins) - else: # no limits given for histogram, both must be calc'd - estbinwidth=(max(inlist)-min(inlist))/float(numbins) +1e-6 #1=>cover all - binsize = ((max(inlist)-min(inlist)+estbinwidth))/float(numbins) - lowerreallimit = min(inlist) - binsize/2 #lower real limit,1st bin - bins = [0]*(numbins) - extrapoints = 0 - for num in inlist: - try: - if (num-lowerreallimit) < 0: - extrapoints = extrapoints + 1 - else: - bintoincrement = int((num-lowerreallimit)/float(binsize)) - bins[bintoincrement] = bins[bintoincrement] + 1 - except: - extrapoints = extrapoints + 1 - if (extrapoints > 0 and printextras == 1): - print '\nPoints outside given histogram range =',extrapoints - return (bins, lowerreallimit, binsize, extrapoints) - - -def lcumfreq(inlist,numbins=10,defaultreallimits=None): - """ -Returns a cumulative frequency histogram, using the histogram function. - -Usage: lcumfreq(inlist,numbins=10,defaultreallimits=None) -Returns: list of cumfreq bin values, lowerreallimit, binsize, extrapoints -""" - h,l,b,e = histogram(inlist,numbins,defaultreallimits) - cumhist = cumsum(copy.deepcopy(h)) - return cumhist,l,b,e - - -def lrelfreq(inlist,numbins=10,defaultreallimits=None): - """ -Returns a relative frequency histogram, using the histogram function. - -Usage: lrelfreq(inlist,numbins=10,defaultreallimits=None) -Returns: list of cumfreq bin values, lowerreallimit, binsize, extrapoints -""" - h,l,b,e = histogram(inlist,numbins,defaultreallimits) - for i in range(len(h)): - h[i] = h[i]/float(len(inlist)) - return h,l,b,e - - -#################################### -##### VARIABILITY FUNCTIONS ###### -#################################### - -def lobrientransform(*args): - """ -Computes a transform on input data (any number of columns). Used to -test for homogeneity of variance prior to running one-way stats. From -Maxwell and Delaney, p.112. - -Usage: lobrientransform(*args) -Returns: transformed data for use in an ANOVA -""" - TINY = 1e-10 - k = len(args) - n = [0.0]*k - v = [0.0]*k - m = [0.0]*k - nargs = [] - for i in range(k): - nargs.append(copy.deepcopy(args[i])) - n[i] = float(len(nargs[i])) - v[i] = var(nargs[i]) - m[i] = mean(nargs[i]) - for j in range(k): - for i in range(n[j]): - t1 = (n[j]-1.5)*n[j]*(nargs[j][i]-m[j])**2 - t2 = 0.5*v[j]*(n[j]-1.0) - t3 = (n[j]-1.0)*(n[j]-2.0) - nargs[j][i] = (t1-t2) / float(t3) - check = 1 - for j in range(k): - if v[j] - mean(nargs[j]) > TINY: - check = 0 - if check <> 1: - raise ValueError, 'Problem in obrientransform.' - else: - return nargs - - -def lsamplevar (inlist): - """ -Returns the variance of the values in the passed list using -N for the denominator (i.e., DESCRIBES the sample variance only). - -Usage: lsamplevar(inlist) -""" - n = len(inlist) - mn = mean(inlist) - deviations = [] - for item in inlist: - deviations.append(item-mn) - return ss(deviations)/float(n) - - -def lsamplestdev (inlist): - """ -Returns the standard deviation of the values in the passed list using -N for the denominator (i.e., DESCRIBES the sample stdev only). - -Usage: lsamplestdev(inlist) -""" - return math.sqrt(samplevar(inlist)) - - -def lcov (x,y, keepdims=0): - """ -Returns the estimated covariance of the values in the passed -array (i.e., N-1). Dimension can equal None (ravel array first), an -integer (the dimension over which to operate), or a sequence (operate -over multiple dimensions). Set keepdims=1 to return an array with the -same number of dimensions as inarray. - -Usage: lcov(x,y,keepdims=0) -""" - - n = len(x) - xmn = mean(x) - ymn = mean(y) - xdeviations = [0]*len(x) - ydeviations = [0]*len(y) - for i in range(len(x)): - xdeviations[i] = x[i] - xmn - ydeviations[i] = y[i] - ymn - ss = 0.0 - for i in range(len(xdeviations)): - ss = ss + xdeviations[i]*ydeviations[i] - return ss/float(n-1) - - -def lvar (inlist): - """ -Returns the variance of the values in the passed list using N-1 -for the denominator (i.e., for estimating population variance). - -Usage: lvar(inlist) -""" - n = len(inlist) - mn = mean(inlist) - deviations = [0]*len(inlist) - for i in range(len(inlist)): - deviations[i] = inlist[i] - mn - return ss(deviations)/float(n-1) - - -def lstdev (inlist): - """ -Returns the standard deviation of the values in the passed list -using N-1 in the denominator (i.e., to estimate population stdev). - -Usage: lstdev(inlist) -""" - return math.sqrt(var(inlist)) - - -def lsterr(inlist): - """ -Returns the standard error of the values in the passed list using N-1 -in the denominator (i.e., to estimate population standard error). - -Usage: lsterr(inlist) -""" - return stdev(inlist) / float(math.sqrt(len(inlist))) - - -def lsem (inlist): - """ -Returns the estimated standard error of the mean (sx-bar) of the -values in the passed list. sem = stdev / sqrt(n) - -Usage: lsem(inlist) -""" - sd = stdev(inlist) - n = len(inlist) - return sd/math.sqrt(n) - - -def lz (inlist, score): - """ -Returns the z-score for a given input score, given that score and the -list from which that score came. Not appropriate for population calculations. - -Usage: lz(inlist, score) -""" - z = (score-mean(inlist))/samplestdev(inlist) - return z - - -def lzs (inlist): - """ -Returns a list of z-scores, one for each score in the passed list. - -Usage: lzs(inlist) -""" - zscores = [] - for item in inlist: - zscores.append(z(inlist,item)) - return zscores - - -#################################### -####### TRIMMING FUNCTIONS ####### -#################################### - -def ltrimboth (l,proportiontocut): - """ -Slices off the passed proportion of items from BOTH ends of the passed -list (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost' -10% of scores. Assumes list is sorted by magnitude. Slices off LESS if -proportion results in a non-integer slice index (i.e., conservatively -slices off proportiontocut). - -Usage: ltrimboth (l,proportiontocut) -Returns: trimmed version of list l -""" - lowercut = int(proportiontocut*len(l)) - uppercut = len(l) - lowercut - return l[lowercut:uppercut] - - -def ltrim1 (l,proportiontocut,tail='right'): - """ -Slices off the passed proportion of items from ONE end of the passed -list (i.e., if proportiontocut=0.1, slices off 'leftmost' or 'rightmost' -10% of scores). Slices off LESS if proportion results in a non-integer -slice index (i.e., conservatively slices off proportiontocut). - -Usage: ltrim1 (l,proportiontocut,tail='right') or set tail='left' -Returns: trimmed version of list l -""" - if tail == 'right': - lowercut = 0 - uppercut = len(l) - int(proportiontocut*len(l)) - elif tail == 'left': - lowercut = int(proportiontocut*len(l)) - uppercut = len(l) - return l[lowercut:uppercut] - - -#################################### -##### CORRELATION FUNCTIONS ###### -#################################### - -def lpaired(x,y): - """ -Interactively determines the type of data and then runs the -appropriated statistic for paired group data. - -Usage: lpaired(x,y) -Returns: appropriate statistic name, value, and probability -""" - samples = '' - while samples not in ['i','r','I','R','c','C']: - print '\nIndependent or related samples, or correlation (i,r,c): ', - samples = raw_input() - - if samples in ['i','I','r','R']: - print '\nComparing variances ...', -# USE O'BRIEN'S TEST FOR HOMOGENEITY OF VARIANCE, Maxwell & delaney, p.112 - r = obrientransform(x,y) - f,p = F_oneway(pstat.colex(r,0),pstat.colex(r,1)) - if p<0.05: - vartype='unequal, p='+str(round(p,4)) - else: - vartype='equal' - print vartype - if samples in ['i','I']: - if vartype[0]=='e': - t,p = ttest_ind(x,y,0) - print '\nIndependent samples t-test: ', round(t,4),round(p,4) - else: - if len(x)>20 or len(y)>20: - z,p = ranksums(x,y) - print '\nRank Sums test (NONparametric, n>20): ', round(z,4),round(p,4) - else: - u,p = mannwhitneyu(x,y) - print '\nMann-Whitney U-test (NONparametric, ns<20): ', round(u,4),round(p,4) - - else: # RELATED SAMPLES - if vartype[0]=='e': - t,p = ttest_rel(x,y,0) - print '\nRelated samples t-test: ', round(t,4),round(p,4) - else: - t,p = ranksums(x,y) - print '\nWilcoxon T-test (NONparametric): ', round(t,4),round(p,4) - else: # CORRELATION ANALYSIS - corrtype = '' - while corrtype not in ['c','C','r','R','d','D']: - print '\nIs the data Continuous, Ranked, or Dichotomous (c,r,d): ', - corrtype = raw_input() - if corrtype in ['c','C']: - m,b,r,p,see = linregress(x,y) - print '\nLinear regression for continuous variables ...' - lol = [['Slope','Intercept','r','Prob','SEestimate'],[round(m,4),round(b,4),round(r,4),round(p,4),round(see,4)]] - pstat.printcc(lol) - elif corrtype in ['r','R']: - r,p = spearmanr(x,y) - print '\nCorrelation for ranked variables ...' - print "Spearman's r: ",round(r,4),round(p,4) - else: # DICHOTOMOUS - r,p = pointbiserialr(x,y) - print '\nAssuming x contains a dichotomous variable ...' - print 'Point Biserial r: ',round(r,4),round(p,4) - print '\n\n' - return None - - -def lpearsonr(x,y): - """ -Calculates a Pearson correlation coefficient and the associated -probability value. Taken from Heiman's Basic Statistics for the Behav. -Sci (2nd), p.195. - -Usage: lpearsonr(x,y) where x and y are equal-length lists -Returns: Pearson's r value, two-tailed p-value -""" - TINY = 1.0e-30 - if len(x) <> len(y): - raise ValueError, 'Input values not paired in pearsonr. Aborting.' - n = len(x) - x = map(float,x) - y = map(float,y) - xmean = mean(x) - ymean = mean(y) - r_num = n*(summult(x,y)) - sum(x)*sum(y) - r_den = math.sqrt((n*ss(x) - square_of_sums(x))*(n*ss(y)-square_of_sums(y))) - r = (r_num / r_den) # denominator already a float - df = n-2 - t = r*math.sqrt(df/((1.0-r+TINY)*(1.0+r+TINY))) - prob = betai(0.5*df,0.5,df/float(df+t*t)) - return r, prob - - -def llincc(x,y): - """ -Calculates Lin's concordance correlation coefficient. - -Usage: alincc(x,y) where x, y are equal-length arrays -Returns: Lin's CC -""" - covar = lcov(x,y)*(len(x)-1)/float(len(x)) # correct denom to n - xvar = lvar(x)*(len(x)-1)/float(len(x)) # correct denom to n - yvar = lvar(y)*(len(y)-1)/float(len(y)) # correct denom to n - lincc = (2 * covar) / ((xvar+yvar) +((amean(x)-amean(y))**2)) - return lincc - - -def lspearmanr(x,y): - """ -Calculates a Spearman rank-order correlation coefficient. Taken -from Heiman's Basic Statistics for the Behav. Sci (1st), p.192. - -Usage: lspearmanr(x,y) where x and y are equal-length lists -Returns: Spearman's r, two-tailed p-value -""" - TINY = 1e-30 - if len(x) <> len(y): - raise ValueError, 'Input values not paired in spearmanr. Aborting.' - n = len(x) - rankx = rankdata(x) - ranky = rankdata(y) - dsq = sumdiffsquared(rankx,ranky) - rs = 1 - 6*dsq / float(n*(n**2-1)) - t = rs * math.sqrt((n-2) / ((rs+1.0)*(1.0-rs))) - df = n-2 - probrs = betai(0.5*df,0.5,df/(df+t*t)) # t already a float -# probability values for rs are from part 2 of the spearman function in -# Numerical Recipies, p.510. They are close to tables, but not exact. (?) - return rs, probrs - - -def lpointbiserialr(x,y): - """ -Calculates a point-biserial correlation coefficient and the associated -probability value. Taken from Heiman's Basic Statistics for the Behav. -Sci (1st), p.194. - -Usage: lpointbiserialr(x,y) where x,y are equal-length lists -Returns: Point-biserial r, two-tailed p-value -""" - TINY = 1e-30 - if len(x) <> len(y): - raise ValueError, 'INPUT VALUES NOT PAIRED IN pointbiserialr. ABORTING.' - data = pstat.abut(x,y) - categories = pstat.unique(x) - if len(categories) <> 2: - raise ValueError, "Exactly 2 categories required for pointbiserialr()." - else: # there are 2 categories, continue - codemap = pstat.abut(categories,range(2)) - recoded = pstat.recode(data,codemap,0) - x = pstat.linexand(data,0,categories[0]) - y = pstat.linexand(data,0,categories[1]) - xmean = mean(pstat.colex(x,1)) - ymean = mean(pstat.colex(y,1)) - n = len(data) - adjust = math.sqrt((len(x)/float(n))*(len(y)/float(n))) - rpb = (ymean - xmean)/samplestdev(pstat.colex(data,1))*adjust - df = n-2 - t = rpb*math.sqrt(df/((1.0-rpb+TINY)*(1.0+rpb+TINY))) - prob = betai(0.5*df,0.5,df/(df+t*t)) # t already a float - return rpb, prob - - -def lkendalltau(x,y): - """ -Calculates Kendall's tau ... correlation of ordinal data. Adapted -from function kendl1 in Numerical Recipies. Needs good test-routine.@@@ - -Usage: lkendalltau(x,y) -Returns: Kendall's tau, two-tailed p-value -""" - n1 = 0 - n2 = 0 - iss = 0 - for j in range(len(x)-1): - for k in range(j,len(y)): - a1 = x[j] - x[k] - a2 = y[j] - y[k] - aa = a1 * a2 - if (aa): # neither list has a tie - n1 = n1 + 1 - n2 = n2 + 1 - if aa > 0: - iss = iss + 1 - else: - iss = iss -1 - else: - if (a1): - n1 = n1 + 1 - else: - n2 = n2 + 1 - tau = iss / math.sqrt(n1*n2) - svar = (4.0*len(x)+10.0) / (9.0*len(x)*(len(x)-1)) - z = tau / math.sqrt(svar) - prob = erfcc(abs(z)/1.4142136) - return tau, prob - - -def llinregress(x,y): - """ -Calculates a regression line on x,y pairs. - -Usage: llinregress(x,y) x,y are equal-length lists of x-y coordinates -Returns: slope, intercept, r, two-tailed prob, sterr-of-estimate -""" - TINY = 1.0e-20 - if len(x) <> len(y): - raise ValueError, 'Input values not paired in linregress. Aborting.' - n = len(x) - x = map(float,x) - y = map(float,y) - xmean = mean(x) - ymean = mean(y) - r_num = float(n*(summult(x,y)) - sum(x)*sum(y)) - r_den = math.sqrt((n*ss(x) - square_of_sums(x))*(n*ss(y)-square_of_sums(y))) - r = r_num / r_den - z = 0.5*math.log((1.0+r+TINY)/(1.0-r+TINY)) - df = n-2 - t = r*math.sqrt(df/((1.0-r+TINY)*(1.0+r+TINY))) - prob = betai(0.5*df,0.5,df/(df+t*t)) - slope = r_num / float(n*ss(x) - square_of_sums(x)) - intercept = ymean - slope*xmean - sterrest = math.sqrt(1-r*r)*samplestdev(y) - return slope, intercept, r, prob, sterrest - - -#################################### -##### INFERENTIAL STATISTICS ##### -#################################### - -def lttest_1samp(a,popmean,printit=0,name='Sample',writemode='a'): - """ -Calculates the t-obtained for the independent samples T-test on ONE group -of scores a, given a population mean. If printit=1, results are printed -to the screen. If printit='filename', the results are output to 'filename' -using the given writemode (default=append). Returns t-value, and prob. - -Usage: lttest_1samp(a,popmean,Name='Sample',printit=0,writemode='a') -Returns: t-value, two-tailed prob -""" - x = mean(a) - v = var(a) - n = len(a) - df = n-1 - svar = ((n-1)*v)/float(df) - t = (x-popmean)/math.sqrt(svar*(1.0/n)) - prob = betai(0.5*df,0.5,float(df)/(df+t*t)) - - if printit <> 0: - statname = 'Single-sample T-test.' - outputpairedstats(printit,writemode, - 'Population','--',popmean,0,0,0, - name,n,x,v,min(a),max(a), - statname,t,prob) - return t,prob - - -def lttest_ind (a, b, printit=0, name1='Samp1', name2='Samp2', writemode='a'): - """ -Calculates the t-obtained T-test on TWO INDEPENDENT samples of -scores a, and b. From Numerical Recipies, p.483. If printit=1, results -are printed to the screen. If printit='filename', the results are output -to 'filename' using the given writemode (default=append). Returns t-value, -and prob. - -Usage: lttest_ind(a,b,printit=0,name1='Samp1',name2='Samp2',writemode='a') -Returns: t-value, two-tailed prob -""" - x1 = mean(a) - x2 = mean(b) - v1 = stdev(a)**2 - v2 = stdev(b)**2 - n1 = len(a) - n2 = len(b) - df = n1+n2-2 - svar = ((n1-1)*v1+(n2-1)*v2)/float(df) - t = (x1-x2)/math.sqrt(svar*(1.0/n1 + 1.0/n2)) - prob = betai(0.5*df,0.5,df/(df+t*t)) - - if printit <> 0: - statname = 'Independent samples T-test.' - outputpairedstats(printit,writemode, - name1,n1,x1,v1,min(a),max(a), - name2,n2,x2,v2,min(b),max(b), - statname,t,prob) - return t,prob - - -def lttest_rel (a,b,printit=0,name1='Sample1',name2='Sample2',writemode='a'): - """ -Calculates the t-obtained T-test on TWO RELATED samples of scores, -a and b. From Numerical Recipies, p.483. If printit=1, results are -printed to the screen. If printit='filename', the results are output to -'filename' using the given writemode (default=append). Returns t-value, -and prob. - -Usage: lttest_rel(a,b,printit=0,name1='Sample1',name2='Sample2',writemode='a') -Returns: t-value, two-tailed prob -""" - if len(a)<>len(b): - raise ValueError, 'Unequal length lists in ttest_rel.' - x1 = mean(a) - x2 = mean(b) - v1 = var(a) - v2 = var(b) - n = len(a) - cov = 0 - for i in range(len(a)): - cov = cov + (a[i]-x1) * (b[i]-x2) - df = n-1 - cov = cov / float(df) - sd = math.sqrt((v1+v2 - 2.0*cov)/float(n)) - t = (x1-x2)/sd - prob = betai(0.5*df,0.5,df/(df+t*t)) - - if printit <> 0: - statname = 'Related samples T-test.' - outputpairedstats(printit,writemode, - name1,n,x1,v1,min(a),max(a), - name2,n,x2,v2,min(b),max(b), - statname,t,prob) - return t, prob - - -def lchisquare(f_obs,f_exp=None): - """ -Calculates a one-way chi square for list of observed frequencies and returns -the result. If no expected frequencies are given, the total N is assumed to -be equally distributed across all groups. - -Usage: lchisquare(f_obs, f_exp=None) f_obs = list of observed cell freq. -Returns: chisquare-statistic, associated p-value -""" - k = len(f_obs) # number of groups - if f_exp == None: - f_exp = [sum(f_obs)/float(k)] * len(f_obs) # create k bins with = freq. - chisq = 0 - for i in range(len(f_obs)): - chisq = chisq + (f_obs[i]-f_exp[i])**2 / float(f_exp[i]) - return chisq, chisqprob(chisq, k-1) - - -def lks_2samp (data1,data2): - """ -Computes the Kolmogorov-Smirnof statistic on 2 samples. From -Numerical Recipies in C, page 493. - -Usage: lks_2samp(data1,data2) data1&2 are lists of values for 2 conditions -Returns: KS D-value, associated p-value -""" - j1 = 0 - j2 = 0 - fn1 = 0.0 - fn2 = 0.0 - n1 = len(data1) - n2 = len(data2) - en1 = n1 - en2 = n2 - d = 0.0 - data1.sort() - data2.sort() - while j1 < n1 and j2 < n2: - d1=data1[j1] - d2=data2[j2] - if d1 <= d2: - fn1 = (j1)/float(en1) - j1 = j1 + 1 - if d2 <= d1: - fn2 = (j2)/float(en2) - j2 = j2 + 1 - dt = (fn2-fn1) - if math.fabs(dt) > math.fabs(d): - d = dt - try: - en = math.sqrt(en1*en2/float(en1+en2)) - prob = ksprob((en+0.12+0.11/en)*abs(d)) - except: - prob = 1.0 - return d, prob - - -def lmannwhitneyu(x,y): - """ -Calculates a Mann-Whitney U statistic on the provided scores and -returns the result. Use only when the n in each condition is < 20 and -you have 2 independent samples of ranks. NOTE: Mann-Whitney U is -significant if the u-obtained is LESS THAN or equal to the critical -value of U found in the tables. Equivalent to Kruskal-Wallis H with -just 2 groups. - -Usage: lmannwhitneyu(data) -Returns: u-statistic, one-tailed p-value (i.e., p(z(U))) -""" - n1 = len(x) - n2 = len(y) - ranked = rankdata(x+y) - rankx = ranked[0:n1] # get the x-ranks - ranky = ranked[n1:] # the rest are y-ranks - u1 = n1*n2 + (n1*(n1+1))/2.0 - sum(rankx) # calc U for x - u2 = n1*n2 - u1 # remainder is U for y - bigu = max(u1,u2) - smallu = min(u1,u2) - T = math.sqrt(tiecorrect(ranked)) # correction factor for tied scores - if T == 0: - raise ValueError, 'All numbers are identical in lmannwhitneyu' - sd = math.sqrt(T*n1*n2*(n1+n2+1)/12.0) - z = abs((bigu-n1*n2/2.0) / sd) # normal approximation for prob calc - return smallu, 1.0 - zprob(z) - - -def ltiecorrect(rankvals): - """ -Corrects for ties in Mann Whitney U and Kruskal Wallis H tests. See -Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences. -New York: McGraw-Hill. Code adapted from |Stat rankind.c code. - -Usage: ltiecorrect(rankvals) -Returns: T correction factor for U or H -""" - sorted,posn = shellsort(rankvals) - n = len(sorted) - T = 0.0 - i = 0 - while (i 20 and you -have 2 independent samples of ranks. - -Usage: lranksums(x,y) -Returns: a z-statistic, two-tailed p-value -""" - n1 = len(x) - n2 = len(y) - alldata = x+y - ranked = rankdata(alldata) - x = ranked[:n1] - y = ranked[n1:] - s = sum(x) - expected = n1*(n1+n2+1) / 2.0 - z = (s - expected) / math.sqrt(n1*n2*(n1+n2+1)/12.0) - prob = 2*(1.0 -zprob(abs(z))) - return z, prob - - -def lwilcoxont(x,y): - """ -Calculates the Wilcoxon T-test for related samples and returns the -result. A non-parametric T-test. - -Usage: lwilcoxont(x,y) -Returns: a t-statistic, two-tail probability estimate -""" - if len(x) <> len(y): - raise ValueError, 'Unequal N in wilcoxont. Aborting.' - d=[] - for i in range(len(x)): - diff = x[i] - y[i] - if diff <> 0: - d.append(diff) - count = len(d) - absd = map(abs,d) - absranked = rankdata(absd) - r_plus = 0.0 - r_minus = 0.0 - for i in range(len(absd)): - if d[i] < 0: - r_minus = r_minus + absranked[i] - else: - r_plus = r_plus + absranked[i] - wt = min(r_plus, r_minus) - mn = count * (count+1) * 0.25 - se = math.sqrt(count*(count+1)*(2.0*count+1.0)/24.0) - z = math.fabs(wt-mn) / se - prob = 2*(1.0 -zprob(abs(z))) - return wt, prob - - -def lkruskalwallish(*args): - """ -The Kruskal-Wallis H-test is a non-parametric ANOVA for 3 or more -groups, requiring at least 5 subjects in each group. This function -calculates the Kruskal-Wallis H-test for 3 or more independent samples -and returns the result. - -Usage: lkruskalwallish(*args) -Returns: H-statistic (corrected for ties), associated p-value -""" - args = list(args) - n = [0]*len(args) - all = [] - n = map(len,args) - for i in range(len(args)): - all = all + args[i] - ranked = rankdata(all) - T = tiecorrect(ranked) - for i in range(len(args)): - args[i] = ranked[0:n[i]] - del ranked[0:n[i]] - rsums = [] - for i in range(len(args)): - rsums.append(sum(args[i])**2) - rsums[i] = rsums[i] / float(n[i]) - ssbn = sum(rsums) - totaln = sum(n) - h = 12.0 / (totaln*(totaln+1)) * ssbn - 3*(totaln+1) - df = len(args) - 1 - if T == 0: - raise ValueError, 'All numbers are identical in lkruskalwallish' - h = h / float(T) - return h, chisqprob(h,df) - - -def lfriedmanchisquare(*args): - """ -Friedman Chi-Square is a non-parametric, one-way within-subjects -ANOVA. This function calculates the Friedman Chi-square test for repeated -measures and returns the result, along with the associated probability -value. It assumes 3 or more repeated measures. Only 3 levels requires a -minimum of 10 subjects in the study. Four levels requires 5 subjects per -level(??). - -Usage: lfriedmanchisquare(*args) -Returns: chi-square statistic, associated p-value -""" - k = len(args) - if k < 3: - raise ValueError, 'Less than 3 levels. Friedman test not appropriate.' - n = len(args[0]) - data = apply(pstat.abut,tuple(args)) - for i in range(len(data)): - data[i] = rankdata(data[i]) - ssbn = 0 - for i in range(k): - ssbn = ssbn + sum(args[i])**2 - chisq = 12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1) - return chisq, chisqprob(chisq,k-1) - - -#################################### -#### PROBABILITY CALCULATIONS #### -#################################### - -def lchisqprob(chisq,df): - """ -Returns the (1-tailed) probability value associated with the provided -chi-square value and df. Adapted from chisq.c in Gary Perlman's |Stat. - -Usage: lchisqprob(chisq,df) -""" - BIG = 20.0 - def ex(x): - BIG = 20.0 - if x < -BIG: - return 0.0 - else: - return math.exp(x) - - if chisq <=0 or df < 1: - return 1.0 - a = 0.5 * chisq - if df%2 == 0: - even = 1 - else: - even = 0 - if df > 1: - y = ex(-a) - if even: - s = y - else: - s = 2.0 * zprob(-math.sqrt(chisq)) - if (df > 2): - chisq = 0.5 * (df - 1.0) - if even: - z = 1.0 - else: - z = 0.5 - if a > BIG: - if even: - e = 0.0 - else: - e = math.log(math.sqrt(math.pi)) - c = math.log(a) - while (z <= chisq): - e = math.log(z) + e - s = s + ex(c*z-a-e) - z = z + 1.0 - return s - else: - if even: - e = 1.0 - else: - e = 1.0 / math.sqrt(math.pi) / math.sqrt(a) - c = 0.0 - while (z <= chisq): - e = e * (a/float(z)) - c = c + e - z = z + 1.0 - return (c*y+s) - else: - return s - - -def lerfcc(x): - """ -Returns the complementary error function erfc(x) with fractional -error everywhere less than 1.2e-7. Adapted from Numerical Recipies. - -Usage: lerfcc(x) -""" - z = abs(x) - t = 1.0 / (1.0+0.5*z) - ans = t * math.exp(-z*z-1.26551223 + t*(1.00002368+t*(0.37409196+t*(0.09678418+t*(-0.18628806+t*(0.27886807+t*(-1.13520398+t*(1.48851587+t*(-0.82215223+t*0.17087277))))))))) - if x >= 0: - return ans - else: - return 2.0 - ans - - -def lzprob(z): - """ -Returns the area under the normal curve 'to the left of' the given z value. -Thus, - for z<0, zprob(z) = 1-tail probability - for z>0, 1.0-zprob(z) = 1-tail probability - for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability -Adapted from z.c in Gary Perlman's |Stat. - -Usage: lzprob(z) -""" - Z_MAX = 6.0 # maximum meaningful z-value - if z == 0.0: - x = 0.0 - else: - y = 0.5 * math.fabs(z) - if y >= (Z_MAX*0.5): - x = 1.0 - elif (y < 1.0): - w = y*y - x = ((((((((0.000124818987 * w - -0.001075204047) * w +0.005198775019) * w - -0.019198292004) * w +0.059054035642) * w - -0.151968751364) * w +0.319152932694) * w - -0.531923007300) * w +0.797884560593) * y * 2.0 - else: - y = y - 2.0 - x = (((((((((((((-0.000045255659 * y - +0.000152529290) * y -0.000019538132) * y - -0.000676904986) * y +0.001390604284) * y - -0.000794620820) * y -0.002034254874) * y - +0.006549791214) * y -0.010557625006) * y - +0.011630447319) * y -0.009279453341) * y - +0.005353579108) * y -0.002141268741) * y - +0.000535310849) * y +0.999936657524 - if z > 0.0: - prob = ((x+1.0)*0.5) - else: - prob = ((1.0-x)*0.5) - return prob - - -def lksprob(alam): - """ -Computes a Kolmolgorov-Smirnov t-test significance level. Adapted from -Numerical Recipies. - -Usage: lksprob(alam) -""" - fac = 2.0 - sum = 0.0 - termbf = 0.0 - a2 = -2.0*alam*alam - for j in range(1,201): - term = fac*math.exp(a2*j*j) - sum = sum + term - if math.fabs(term) <= (0.001*termbf) or math.fabs(term) < (1.0e-8*sum): - return sum - fac = -fac - termbf = math.fabs(term) - return 1.0 # Get here only if fails to converge; was 0.0!! - - -def lfprob (dfnum, dfden, F): - """ -Returns the (1-tailed) significance level (p-value) of an F -statistic given the degrees of freedom for the numerator (dfR-dfF) and -the degrees of freedom for the denominator (dfF). - -Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn -""" - p = betai(0.5*dfden, 0.5*dfnum, dfden/float(dfden+dfnum*F)) - return p - - -def lbetacf(a,b,x): - """ -This function evaluates the continued fraction form of the incomplete -Beta function, betai. (Adapted from: Numerical Recipies in C.) - -Usage: lbetacf(a,b,x) -""" - ITMAX = 200 - EPS = 3.0e-7 - - bm = az = am = 1.0 - qab = a+b - qap = a+1.0 - qam = a-1.0 - bz = 1.0-qab*x/qap - for i in range(ITMAX+1): - em = float(i+1) - tem = em + em - d = em*(b-em)*x/((qam+tem)*(a+tem)) - ap = az + d*am - bp = bz+d*bm - d = -(a+em)*(qab+em)*x/((qap+tem)*(a+tem)) - app = ap+d*az - bpp = bp+d*bz - aold = az - am = ap/bpp - bm = bp/bpp - az = app/bpp - bz = 1.0 - if (abs(az-aold)<(EPS*abs(az))): - return az - print 'a or b too big, or ITMAX too small in Betacf.' - - -def lgammln(xx): - """ -Returns the gamma function of xx. - Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt. -(Adapted from: Numerical Recipies in C.) - -Usage: lgammln(xx) -""" - - coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516, - 0.120858003e-2, -0.536382e-5] - x = xx - 1.0 - tmp = x + 5.5 - tmp = tmp - (x+0.5)*math.log(tmp) - ser = 1.0 - for j in range(len(coeff)): - x = x + 1 - ser = ser + coeff[j]/x - return -tmp + math.log(2.50662827465*ser) - - -def lbetai(a,b,x): - """ -Returns the incomplete beta function: - - I-sub-x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt) - -where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma -function of a. The continued fraction formulation is implemented here, -using the betacf function. (Adapted from: Numerical Recipies in C.) - -Usage: lbetai(a,b,x) -""" - if (x<0.0 or x>1.0): - raise ValueError, 'Bad x in lbetai' - if (x==0.0 or x==1.0): - bt = 0.0 - else: - bt = math.exp(gammln(a+b)-gammln(a)-gammln(b)+a*math.log(x)+b* - math.log(1.0-x)) - if (x<(a+1.0)/(a+b+2.0)): - return bt*betacf(a,b,x)/float(a) - else: - return 1.0-bt*betacf(b,a,1.0-x)/float(b) - - -#################################### -####### ANOVA CALCULATIONS ####### -#################################### - -def lF_oneway(*lists): - """ -Performs a 1-way ANOVA, returning an F-value and probability given -any number of groups. From Heiman, pp.394-7. - -Usage: F_oneway(*lists) where *lists is any number of lists, one per - treatment group -Returns: F value, one-tailed p-value -""" - a = len(lists) # ANOVA on 'a' groups, each in it's own list - means = [0]*a - vars = [0]*a - ns = [0]*a - alldata = [] - tmp = map(N.array,lists) - means = map(amean,tmp) - vars = map(avar,tmp) - ns = map(len,lists) - for i in range(len(lists)): - alldata = alldata + lists[i] - alldata = N.array(alldata) - bign = len(alldata) - sstot = ass(alldata)-(asquare_of_sums(alldata)/float(bign)) - ssbn = 0 - for list in lists: - ssbn = ssbn + asquare_of_sums(N.array(list))/float(len(list)) - ssbn = ssbn - (asquare_of_sums(alldata)/float(bign)) - sswn = sstot-ssbn - dfbn = a-1 - dfwn = bign - a - msb = ssbn/float(dfbn) - msw = sswn/float(dfwn) - f = msb/msw - prob = fprob(dfbn,dfwn,f) - return f, prob - - -def lF_value (ER,EF,dfnum,dfden): - """ -Returns an F-statistic given the following: - ER = error associated with the null hypothesis (the Restricted model) - EF = error associated with the alternate hypothesis (the Full model) - dfR-dfF = degrees of freedom of the numerator - dfF = degrees of freedom associated with the denominator/Full model - -Usage: lF_value(ER,EF,dfnum,dfden) -""" - return ((ER-EF)/float(dfnum) / (EF/float(dfden))) - - -#################################### -######## SUPPORT FUNCTIONS ####### -#################################### - -def writecc (listoflists,file,writetype='w',extra=2): - """ -Writes a list of lists to a file in columns, customized by the max -size of items within the columns (max size of items in col, +2 characters) -to specified file. File-overwrite is the default. - -Usage: writecc (listoflists,file,writetype='w',extra=2) -Returns: None -""" - if type(listoflists[0]) not in [ListType,TupleType]: - listoflists = [listoflists] - outfile = open(file,writetype) - rowstokill = [] - list2print = copy.deepcopy(listoflists) - for i in range(len(listoflists)): - if listoflists[i] == ['\n'] or listoflists[i]=='\n' or listoflists[i]=='dashes': - rowstokill = rowstokill + [i] - rowstokill.reverse() - for row in rowstokill: - del list2print[row] - maxsize = [0]*len(list2print[0]) - for col in range(len(list2print[0])): - items = pstat.colex(list2print,col) - items = map(pstat.makestr,items) - maxsize[col] = max(map(len,items)) + extra - for row in listoflists: - if row == ['\n'] or row == '\n': - outfile.write('\n') - elif row == ['dashes'] or row == 'dashes': - dashes = [0]*len(maxsize) - for j in range(len(maxsize)): - dashes[j] = '-'*(maxsize[j]-2) - outfile.write(pstat.lineincustcols(dashes,maxsize)) - else: - outfile.write(pstat.lineincustcols(row,maxsize)) - outfile.write('\n') - outfile.close() - return None - - -def lincr(l,cap): # to increment a list up to a max-list of 'cap' - """ -Simulate a counting system from an n-dimensional list. - -Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n -Returns: next set of values for list l, OR -1 (if overflow) -""" - l[0] = l[0] + 1 # e.g., [0,0,0] --> [2,4,3] (=cap) - for i in range(len(l)): - if l[i] > cap[i] and i < len(l)-1: # if carryover AND not done - l[i] = 0 - l[i+1] = l[i+1] + 1 - elif l[i] > cap[i] and i == len(l)-1: # overflow past last column, must be finished - l = -1 - return l - - -def lsum (inlist): - """ -Returns the sum of the items in the passed list. - -Usage: lsum(inlist) -""" - s = 0 - for item in inlist: - s = s + item - return s - - -def lcumsum (inlist): - """ -Returns a list consisting of the cumulative sum of the items in the -passed list. - -Usage: lcumsum(inlist) -""" - newlist = copy.deepcopy(inlist) - for i in range(1,len(newlist)): - newlist[i] = newlist[i] + newlist[i-1] - return newlist - - -def lss(inlist): - """ -Squares each value in the passed list, adds up these squares and -returns the result. - -Usage: lss(inlist) -""" - ss = 0 - for item in inlist: - ss = ss + item*item - return ss - - -def lsummult (list1,list2): - """ -Multiplies elements in list1 and list2, element by element, and -returns the sum of all resulting multiplications. Must provide equal -length lists. - -Usage: lsummult(list1,list2) -""" - if len(list1) <> len(list2): - raise ValueError, "Lists not equal length in summult." - s = 0 - for item1,item2 in pstat.abut(list1,list2): - s = s + item1*item2 - return s - - -def lsumdiffsquared(x,y): - """ -Takes pairwise differences of the values in lists x and y, squares -these differences, and returns the sum of these squares. - -Usage: lsumdiffsquared(x,y) -Returns: sum[(x[i]-y[i])**2] -""" - sds = 0 - for i in range(len(x)): - sds = sds + (x[i]-y[i])**2 - return sds - - -def lsquare_of_sums(inlist): - """ -Adds the values in the passed list, squares the sum, and returns -the result. - -Usage: lsquare_of_sums(inlist) -Returns: sum(inlist[i])**2 -""" - s = sum(inlist) - return float(s)*s - - -def lshellsort(inlist): - """ -Shellsort algorithm. Sorts a 1D-list. - -Usage: lshellsort(inlist) -Returns: sorted-inlist, sorting-index-vector (for original list) -""" - n = len(inlist) - svec = copy.deepcopy(inlist) - ivec = range(n) - gap = n/2 # integer division needed - while gap >0: - for i in range(gap,n): - for j in range(i-gap,-1,-gap): - while j>=0 and svec[j]>svec[j+gap]: - temp = svec[j] - svec[j] = svec[j+gap] - svec[j+gap] = temp - itemp = ivec[j] - ivec[j] = ivec[j+gap] - ivec[j+gap] = itemp - gap = gap / 2 # integer division needed -# svec is now sorted inlist, and ivec has the order svec[i] = vec[ivec[i]] - return svec, ivec - - -def lrankdata(inlist): - """ -Ranks the data in inlist, dealing with ties appropritely. Assumes -a 1D inlist. Adapted from Gary Perlman's |Stat ranksort. - -Usage: lrankdata(inlist) -Returns: a list of length equal to inlist, containing rank scores -""" - n = len(inlist) - svec, ivec = shellsort(inlist) - sumranks = 0 - dupcount = 0 - newlist = [0]*n - for i in range(n): - sumranks = sumranks + i - dupcount = dupcount + 1 - if i==n-1 or svec[i] <> svec[i+1]: - averank = sumranks / float(dupcount) + 1 - for j in range(i-dupcount+1,i+1): - newlist[ivec[j]] = averank - sumranks = 0 - dupcount = 0 - return newlist - - -def outputpairedstats(fname,writemode,name1,n1,m1,se1,min1,max1,name2,n2,m2,se2,min2,max2,statname,stat,prob): - """ -Prints or write to a file stats for two groups, using the name, n, -mean, sterr, min and max for each group, as well as the statistic name, -its value, and the associated p-value. - -Usage: outputpairedstats(fname,writemode, - name1,n1,mean1,stderr1,min1,max1, - name2,n2,mean2,stderr2,min2,max2, - statname,stat,prob) -Returns: None -""" - suffix = '' # for *s after the p-value - try: - x = prob.shape - prob = prob[0] - except: - pass - if prob < 0.001: suffix = ' ***' - elif prob < 0.01: suffix = ' **' - elif prob < 0.05: suffix = ' *' - title = [['Name','N','Mean','SD','Min','Max']] - lofl = title+[[name1,n1,round(m1,3),round(math.sqrt(se1),3),min1,max1], - [name2,n2,round(m2,3),round(math.sqrt(se2),3),min2,max2]] - if type(fname)<>StringType or len(fname)==0: - print - print statname - print - pstat.printcc(lofl) - print - try: - if stat.shape == (): - stat = stat[0] - if prob.shape == (): - prob = prob[0] - except: - pass - print 'Test statistic = ',round(stat,3),' p = ',round(prob,3),suffix - print - else: - file = open(fname,writemode) - file.write('\n'+statname+'\n\n') - file.close() - writecc(lofl,fname,'a') - file = open(fname,'a') - try: - if stat.shape == (): - stat = stat[0] - if prob.shape == (): - prob = prob[0] - except: - pass - file.write(pstat.list2string(['\nTest statistic = ',round(stat,4),' p = ',round(prob,4),suffix,'\n\n'])) - file.close() - return None - - -def lfindwithin (data): - """ -Returns an integer representing a binary vector, where 1=within- -subject factor, 0=between. Input equals the entire data 2D list (i.e., -column 0=random factor, column -1=measured values (those two are skipped). -Note: input data is in |Stat format ... a list of lists ("2D list") with -one row per measured value, first column=subject identifier, last column= -score, one in-between column per factor (these columns contain level -designations on each factor). See also stats.anova.__doc__. - -Usage: lfindwithin(data) data in |Stat format -""" - - numfact = len(data[0])-1 - withinvec = 0 - for col in range(1,numfact): - examplelevel = pstat.unique(pstat.colex(data,col))[0] - rows = pstat.linexand(data,col,examplelevel) # get 1 level of this factor - factsubjs = pstat.unique(pstat.colex(rows,0)) - allsubjs = pstat.unique(pstat.colex(data,0)) - if len(factsubjs) == len(allsubjs): # fewer Ss than scores on this factor? - withinvec = withinvec + (1 << col) - return withinvec - - -######################################################### -######################################################### -####### DISPATCH LISTS AND TUPLES TO ABOVE FCNS ######### -######################################################### -######################################################### - -## CENTRAL TENDENCY: -geometricmean = Dispatch ( (lgeometricmean, (ListType, TupleType)), ) -harmonicmean = Dispatch ( (lharmonicmean, (ListType, TupleType)), ) -mean = Dispatch ( (lmean, (ListType, TupleType)), ) -median = Dispatch ( (lmedian, (ListType, TupleType)), ) -medianscore = Dispatch ( (lmedianscore, (ListType, TupleType)), ) -mode = Dispatch ( (lmode, (ListType, TupleType)), ) - -## MOMENTS: -moment = Dispatch ( (lmoment, (ListType, TupleType)), ) -variation = Dispatch ( (lvariation, (ListType, TupleType)), ) -skew = Dispatch ( (lskew, (ListType, TupleType)), ) -kurtosis = Dispatch ( (lkurtosis, (ListType, TupleType)), ) -describe = Dispatch ( (ldescribe, (ListType, TupleType)), ) - -## FREQUENCY STATISTICS: -itemfreq = Dispatch ( (litemfreq, (ListType, TupleType)), ) -scoreatpercentile = Dispatch ( (lscoreatpercentile, (ListType, TupleType)), ) -percentileofscore = Dispatch ( (lpercentileofscore, (ListType, TupleType)), ) -histogram = Dispatch ( (lhistogram, (ListType, TupleType)), ) -cumfreq = Dispatch ( (lcumfreq, (ListType, TupleType)), ) -relfreq = Dispatch ( (lrelfreq, (ListType, TupleType)), ) - -## VARIABILITY: -obrientransform = Dispatch ( (lobrientransform, (ListType, TupleType)), ) -samplevar = Dispatch ( (lsamplevar, (ListType, TupleType)), ) -samplestdev = Dispatch ( (lsamplestdev, (ListType, TupleType)), ) -var = Dispatch ( (lvar, (ListType, TupleType)), ) -stdev = Dispatch ( (lstdev, (ListType, TupleType)), ) -sterr = Dispatch ( (lsterr, (ListType, TupleType)), ) -sem = Dispatch ( (lsem, (ListType, TupleType)), ) -z = Dispatch ( (lz, (ListType, TupleType)), ) -zs = Dispatch ( (lzs, (ListType, TupleType)), ) - -## TRIMMING FCNS: -trimboth = Dispatch ( (ltrimboth, (ListType, TupleType)), ) -trim1 = Dispatch ( (ltrim1, (ListType, TupleType)), ) - -## CORRELATION FCNS: -paired = Dispatch ( (lpaired, (ListType, TupleType)), ) -pearsonr = Dispatch ( (lpearsonr, (ListType, TupleType)), ) -spearmanr = Dispatch ( (lspearmanr, (ListType, TupleType)), ) -pointbiserialr = Dispatch ( (lpointbiserialr, (ListType, TupleType)), ) -kendalltau = Dispatch ( (lkendalltau, (ListType, TupleType)), ) -linregress = Dispatch ( (llinregress, (ListType, TupleType)), ) - -## INFERENTIAL STATS: -ttest_1samp = Dispatch ( (lttest_1samp, (ListType, TupleType)), ) -ttest_ind = Dispatch ( (lttest_ind, (ListType, TupleType)), ) -ttest_rel = Dispatch ( (lttest_rel, (ListType, TupleType)), ) -chisquare = Dispatch ( (lchisquare, (ListType, TupleType)), ) -ks_2samp = Dispatch ( (lks_2samp, (ListType, TupleType)), ) -mannwhitneyu = Dispatch ( (lmannwhitneyu, (ListType, TupleType)), ) -ranksums = Dispatch ( (lranksums, (ListType, TupleType)), ) -tiecorrect = Dispatch ( (ltiecorrect, (ListType, TupleType)), ) -wilcoxont = Dispatch ( (lwilcoxont, (ListType, TupleType)), ) -kruskalwallish = Dispatch ( (lkruskalwallish, (ListType, TupleType)), ) -friedmanchisquare = Dispatch ( (lfriedmanchisquare, (ListType, TupleType)), ) - -## PROBABILITY CALCS: -chisqprob = Dispatch ( (lchisqprob, (IntType, FloatType)), ) -zprob = Dispatch ( (lzprob, (IntType, FloatType)), ) -ksprob = Dispatch ( (lksprob, (IntType, FloatType)), ) -fprob = Dispatch ( (lfprob, (IntType, FloatType)), ) -betacf = Dispatch ( (lbetacf, (IntType, FloatType)), ) -betai = Dispatch ( (lbetai, (IntType, FloatType)), ) -erfcc = Dispatch ( (lerfcc, (IntType, FloatType)), ) -gammln = Dispatch ( (lgammln, (IntType, FloatType)), ) - -## ANOVA FUNCTIONS: -F_oneway = Dispatch ( (lF_oneway, (ListType, TupleType)), ) -F_value = Dispatch ( (lF_value, (ListType, TupleType)), ) - -## SUPPORT FUNCTIONS: -incr = Dispatch ( (lincr, (ListType, TupleType)), ) -sum = Dispatch ( (lsum, (ListType, TupleType)), ) -cumsum = Dispatch ( (lcumsum, (ListType, TupleType)), ) -ss = Dispatch ( (lss, (ListType, TupleType)), ) -summult = Dispatch ( (lsummult, (ListType, TupleType)), ) -square_of_sums = Dispatch ( (lsquare_of_sums, (ListType, TupleType)), ) -sumdiffsquared = Dispatch ( (lsumdiffsquared, (ListType, TupleType)), ) -shellsort = Dispatch ( (lshellsort, (ListType, TupleType)), ) -rankdata = Dispatch ( (lrankdata, (ListType, TupleType)), ) -findwithin = Dispatch ( (lfindwithin, (ListType, TupleType)), ) - - -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== -#============= THE ARRAY-VERSION OF THE STATS FUNCTIONS =============== - -try: # DEFINE THESE *ONLY* IF NUMERIC IS AVAILABLE - import numpy as N - import numpy.linalg as LA - - -##################################### -######## ACENTRAL TENDENCY ######## -##################################### - - def ageometricmean (inarray,dimension=None,keepdims=0): - """ -Calculates the geometric mean of the values in the passed array. -That is: n-th root of (x1 * x2 * ... * xn). Defaults to ALL values in -the passed array. Use dimension=None to flatten array first. REMEMBER: if -dimension=0, it collapses over dimension 0 ('rows' in a 2D array) only, and -if dimension is a sequence, it collapses over all specified dimensions. If -keepdims is set to 1, the resulting array will have as many dimensions as -inarray, with only 1 'level' per dim that was collapsed over. - -Usage: ageometricmean(inarray,dimension=None,keepdims=0) -Returns: geometric mean computed over dim(s) listed in dimension -""" - inarray = N.array(inarray,N.float_) - if dimension == None: - inarray = N.ravel(inarray) - size = len(inarray) - mult = N.power(inarray,1.0/size) - mult = N.multiply.reduce(mult) - elif type(dimension) in [IntType,FloatType]: - size = inarray.shape[dimension] - mult = N.power(inarray,1.0/size) - mult = N.multiply.reduce(mult,dimension) - if keepdims == 1: - shp = list(inarray.shape) - shp[dimension] = 1 - sum = N.reshape(sum,shp) - else: # must be a SEQUENCE of dims to average over - dims = list(dimension) - dims.sort() - dims.reverse() - size = N.array(N.multiply.reduce(N.take(inarray.shape,dims)),N.float_) - mult = N.power(inarray,1.0/size) - for dim in dims: - mult = N.multiply.reduce(mult,dim) - if keepdims == 1: - shp = list(inarray.shape) - for dim in dims: - shp[dim] = 1 - mult = N.reshape(mult,shp) - return mult - - - def aharmonicmean (inarray,dimension=None,keepdims=0): - """ -Calculates the harmonic mean of the values in the passed array. -That is: n / (1/x1 + 1/x2 + ... + 1/xn). Defaults to ALL values in -the passed array. Use dimension=None to flatten array first. REMEMBER: if -dimension=0, it collapses over dimension 0 ('rows' in a 2D array) only, and -if dimension is a sequence, it collapses over all specified dimensions. If -keepdims is set to 1, the resulting array will have as many dimensions as -inarray, with only 1 'level' per dim that was collapsed over. - -Usage: aharmonicmean(inarray,dimension=None,keepdims=0) -Returns: harmonic mean computed over dim(s) in dimension -""" - inarray = inarray.astype(N.float_) - if dimension == None: - inarray = N.ravel(inarray) - size = len(inarray) - s = N.add.reduce(1.0 / inarray) - elif type(dimension) in [IntType,FloatType]: - size = float(inarray.shape[dimension]) - s = N.add.reduce(1.0/inarray, dimension) - if keepdims == 1: - shp = list(inarray.shape) - shp[dimension] = 1 - s = N.reshape(s,shp) - else: # must be a SEQUENCE of dims to average over - dims = list(dimension) - dims.sort() - nondims = [] - for i in range(len(inarray.shape)): - if i not in dims: - nondims.append(i) - tinarray = N.transpose(inarray,nondims+dims) # put keep-dims first - idx = [0] *len(nondims) - if idx == []: - size = len(N.ravel(inarray)) - s = asum(1.0 / inarray) - if keepdims == 1: - s = N.reshape([s],N.ones(len(inarray.shape))) - else: - idx[0] = -1 - loopcap = N.array(tinarray.shape[0:len(nondims)]) -1 - s = N.zeros(loopcap+1,N.float_) - while incr(idx,loopcap) <> -1: - s[idx] = asum(1.0/tinarray[idx]) - size = N.multiply.reduce(N.take(inarray.shape,dims)) - if keepdims == 1: - shp = list(inarray.shape) - for dim in dims: - shp[dim] = 1 - s = N.reshape(s,shp) - return size / s - - - def amean (inarray,dimension=None,keepdims=0): - """ -Calculates the arithmatic mean of the values in the passed array. -That is: 1/n * (x1 + x2 + ... + xn). Defaults to ALL values in the -passed array. Use dimension=None to flatten array first. REMEMBER: if -dimension=0, it collapses over dimension 0 ('rows' in a 2D array) only, and -if dimension is a sequence, it collapses over all specified dimensions. If -keepdims is set to 1, the resulting array will have as many dimensions as -inarray, with only 1 'level' per dim that was collapsed over. - -Usage: amean(inarray,dimension=None,keepdims=0) -Returns: arithematic mean calculated over dim(s) in dimension -""" - if inarray.dtype in [N.int_, N.short,N.ubyte]: - inarray = inarray.astype(N.float_) - if dimension == None: - inarray = N.ravel(inarray) - sum = N.add.reduce(inarray) - denom = float(len(inarray)) - elif type(dimension) in [IntType,FloatType]: - sum = asum(inarray,dimension) - denom = float(inarray.shape[dimension]) - if keepdims == 1: - shp = list(inarray.shape) - shp[dimension] = 1 - sum = N.reshape(sum,shp) - else: # must be a TUPLE of dims to average over - dims = list(dimension) - dims.sort() - dims.reverse() - sum = inarray *1.0 - for dim in dims: - sum = N.add.reduce(sum,dim) - denom = N.array(N.multiply.reduce(N.take(inarray.shape,dims)),N.float_) - if keepdims == 1: - shp = list(inarray.shape) - for dim in dims: - shp[dim] = 1 - sum = N.reshape(sum,shp) - return sum/denom - - - def amedian (inarray,numbins=1000): - """ -Calculates the COMPUTED median value of an array of numbers, given the -number of bins to use for the histogram (more bins approaches finding the -precise median value of the array; default number of bins = 1000). From -G.W. Heiman's Basic Stats, or CRC Probability & Statistics. -NOTE: THIS ROUTINE ALWAYS uses the entire passed array (flattens it first). - -Usage: amedian(inarray,numbins=1000) -Returns: median calculated over ALL values in inarray -""" - inarray = N.ravel(inarray) - (hist, smallest, binsize, extras) = ahistogram(inarray,numbins,[min(inarray),max(inarray)]) - cumhist = N.cumsum(hist) # make cumulative histogram - otherbins = N.greater_equal(cumhist,len(inarray)/2.0) - otherbins = list(otherbins) # list of 0/1s, 1s start at median bin - cfbin = otherbins.index(1) # get 1st(!) index holding 50%ile score - LRL = smallest + binsize*cfbin # get lower read limit of that bin - cfbelow = N.add.reduce(hist[0:cfbin]) # cum. freq. below bin - freq = hist[cfbin] # frequency IN the 50%ile bin - median = LRL + ((len(inarray)/2.0-cfbelow)/float(freq))*binsize # MEDIAN - return median - - - def amedianscore (inarray,dimension=None): - """ -Returns the 'middle' score of the passed array. If there is an even -number of scores, the mean of the 2 middle scores is returned. Can function -with 1D arrays, or on the FIRST dimension of 2D arrays (i.e., dimension can -be None, to pre-flatten the array, or else dimension must equal 0). - -Usage: amedianscore(inarray,dimension=None) -Returns: 'middle' score of the array, or the mean of the 2 middle scores -""" - if dimension == None: - inarray = N.ravel(inarray) - dimension = 0 - inarray = N.sort(inarray,dimension) - if inarray.shape[dimension] % 2 == 0: # if even number of elements - indx = inarray.shape[dimension]/2 # integer division correct - median = N.asarray(inarray[indx]+inarray[indx-1]) / 2.0 - else: - indx = inarray.shape[dimension] / 2 # integer division correct - median = N.take(inarray,[indx],dimension) - if median.shape == (1,): - median = median[0] - return median - - - def amode(a, dimension=None): - """ -Returns an array of the modal (most common) score in the passed array. -If there is more than one such score, ONLY THE FIRST is returned. -The bin-count for the modal values is also returned. Operates on whole -array (dimension=None), or on a given dimension. - -Usage: amode(a, dimension=None) -Returns: array of bin-counts for mode(s), array of corresponding modal values -""" - - if dimension == None: - a = N.ravel(a) - dimension = 0 - scores = pstat.aunique(N.ravel(a)) # get ALL unique values - testshape = list(a.shape) - testshape[dimension] = 1 - oldmostfreq = N.zeros(testshape) - oldcounts = N.zeros(testshape) - for score in scores: - template = N.equal(a,score) - counts = asum(template,dimension,1) - mostfrequent = N.where(counts>oldcounts,score,oldmostfreq) - oldcounts = N.where(counts>oldcounts,counts,oldcounts) - oldmostfreq = mostfrequent - return oldcounts, mostfrequent - - - def atmean(a,limits=None,inclusive=(1,1)): - """ -Returns the arithmetic mean of all values in an array, ignoring values -strictly outside the sequence passed to 'limits'. Note: either limit -in the sequence, or the value of limits itself, can be set to None. The -inclusive list/tuple determines whether the lower and upper limiting bounds -(respectively) are open/exclusive (0) or closed/inclusive (1). - -Usage: atmean(a,limits=None,inclusive=(1,1)) -""" - if a.dtype in [N.int_, N.short,N.ubyte]: - a = a.astype(N.float_) - if limits == None: - return mean(a) - assert type(limits) in [ListType,TupleType,N.ndarray], "Wrong type for limits in atmean" - if inclusive[0]: lowerfcn = N.greater_equal - else: lowerfcn = N.greater - if inclusive[1]: upperfcn = N.less_equal - else: upperfcn = N.less - if limits[0] > N.maximum.reduce(N.ravel(a)) or limits[1] < N.minimum.reduce(N.ravel(a)): - raise ValueError, "No array values within given limits (atmean)." - elif limits[0]==None and limits[1]<>None: - mask = upperfcn(a,limits[1]) - elif limits[0]<>None and limits[1]==None: - mask = lowerfcn(a,limits[0]) - elif limits[0]<>None and limits[1]<>None: - mask = lowerfcn(a,limits[0])*upperfcn(a,limits[1]) - s = float(N.add.reduce(N.ravel(a*mask))) - n = float(N.add.reduce(N.ravel(mask))) - return s/n - - - def atvar(a,limits=None,inclusive=(1,1)): - """ -Returns the sample variance of values in an array, (i.e., using N-1), -ignoring values strictly outside the sequence passed to 'limits'. -Note: either limit in the sequence, or the value of limits itself, -can be set to None. The inclusive list/tuple determines whether the lower -and upper limiting bounds (respectively) are open/exclusive (0) or -closed/inclusive (1). ASSUMES A FLAT ARRAY (OR ELSE PREFLATTENS). - -Usage: atvar(a,limits=None,inclusive=(1,1)) -""" - a = a.astype(N.float_) - if limits == None or limits == [None,None]: - return avar(a) - assert type(limits) in [ListType,TupleType,N.ndarray], "Wrong type for limits in atvar" - if inclusive[0]: lowerfcn = N.greater_equal - else: lowerfcn = N.greater - if inclusive[1]: upperfcn = N.less_equal - else: upperfcn = N.less - if limits[0] > N.maximum.reduce(N.ravel(a)) or limits[1] < N.minimum.reduce(N.ravel(a)): - raise ValueError, "No array values within given limits (atvar)." - elif limits[0]==None and limits[1]<>None: - mask = upperfcn(a,limits[1]) - elif limits[0]<>None and limits[1]==None: - mask = lowerfcn(a,limits[0]) - elif limits[0]<>None and limits[1]<>None: - mask = lowerfcn(a,limits[0])*upperfcn(a,limits[1]) - - a = N.compress(mask,a) # squish out excluded values - return avar(a) - - - def atmin(a,lowerlimit=None,dimension=None,inclusive=1): - """ -Returns the minimum value of a, along dimension, including only values less -than (or equal to, if inclusive=1) lowerlimit. If the limit is set to None, -all values in the array are used. - -Usage: atmin(a,lowerlimit=None,dimension=None,inclusive=1) -""" - if inclusive: lowerfcn = N.greater - else: lowerfcn = N.greater_equal - if dimension == None: - a = N.ravel(a) - dimension = 0 - if lowerlimit == None: - lowerlimit = N.minimum.reduce(N.ravel(a))-11 - biggest = N.maximum.reduce(N.ravel(a)) - ta = N.where(lowerfcn(a,lowerlimit),a,biggest) - return N.minimum.reduce(ta,dimension) - - - def atmax(a,upperlimit,dimension=None,inclusive=1): - """ -Returns the maximum value of a, along dimension, including only values greater -than (or equal to, if inclusive=1) upperlimit. If the limit is set to None, -a limit larger than the max value in the array is used. - -Usage: atmax(a,upperlimit,dimension=None,inclusive=1) -""" - if inclusive: upperfcn = N.less - else: upperfcn = N.less_equal - if dimension == None: - a = N.ravel(a) - dimension = 0 - if upperlimit == None: - upperlimit = N.maximum.reduce(N.ravel(a))+1 - smallest = N.minimum.reduce(N.ravel(a)) - ta = N.where(upperfcn(a,upperlimit),a,smallest) - return N.maximum.reduce(ta,dimension) - - - def atstdev(a,limits=None,inclusive=(1,1)): - """ -Returns the standard deviation of all values in an array, ignoring values -strictly outside the sequence passed to 'limits'. Note: either limit -in the sequence, or the value of limits itself, can be set to None. The -inclusive list/tuple determines whether the lower and upper limiting bounds -(respectively) are open/exclusive (0) or closed/inclusive (1). - -Usage: atstdev(a,limits=None,inclusive=(1,1)) -""" - return N.sqrt(tvar(a,limits,inclusive)) - - - def atsem(a,limits=None,inclusive=(1,1)): - """ -Returns the standard error of the mean for the values in an array, -(i.e., using N for the denominator), ignoring values strictly outside -the sequence passed to 'limits'. Note: either limit in the sequence, -or the value of limits itself, can be set to None. The inclusive list/tuple -determines whether the lower and upper limiting bounds (respectively) are -open/exclusive (0) or closed/inclusive (1). - -Usage: atsem(a,limits=None,inclusive=(1,1)) -""" - sd = tstdev(a,limits,inclusive) - if limits == None or limits == [None,None]: - n = float(len(N.ravel(a))) - limits = [min(a)-1, max(a)+1] - assert type(limits) in [ListType,TupleType,N.ndarray], "Wrong type for limits in atsem" - if inclusive[0]: lowerfcn = N.greater_equal - else: lowerfcn = N.greater - if inclusive[1]: upperfcn = N.less_equal - else: upperfcn = N.less - if limits[0] > N.maximum.reduce(N.ravel(a)) or limits[1] < N.minimum.reduce(N.ravel(a)): - raise ValueError, "No array values within given limits (atsem)." - elif limits[0]==None and limits[1]<>None: - mask = upperfcn(a,limits[1]) - elif limits[0]<>None and limits[1]==None: - mask = lowerfcn(a,limits[0]) - elif limits[0]<>None and limits[1]<>None: - mask = lowerfcn(a,limits[0])*upperfcn(a,limits[1]) - term1 = N.add.reduce(N.ravel(a*a*mask)) - n = float(N.add.reduce(N.ravel(mask))) - return sd/math.sqrt(n) - - -##################################### -############ AMOMENTS ############# -##################################### - - def amoment(a,moment=1,dimension=None): - """ -Calculates the nth moment about the mean for a sample (defaults to the -1st moment). Generally used to calculate coefficients of skewness and -kurtosis. Dimension can equal None (ravel array first), an integer -(the dimension over which to operate), or a sequence (operate over -multiple dimensions). - -Usage: amoment(a,moment=1,dimension=None) -Returns: appropriate moment along given dimension -""" - if dimension == None: - a = N.ravel(a) - dimension = 0 - if moment == 1: - return 0.0 - else: - mn = amean(a,dimension,1) # 1=keepdims - s = N.power((a-mn),moment) - return amean(s,dimension) - - - def avariation(a,dimension=None): - """ -Returns the coefficient of variation, as defined in CRC Standard -Probability and Statistics, p.6. Dimension can equal None (ravel array -first), an integer (the dimension over which to operate), or a -sequence (operate over multiple dimensions). - -Usage: avariation(a,dimension=None) -""" - return 100.0*asamplestdev(a,dimension)/amean(a,dimension) - - - def askew(a,dimension=None): - """ -Returns the skewness of a distribution (normal ==> 0.0; >0 means extra -weight in left tail). Use askewtest() to see if it's close enough. -Dimension can equal None (ravel array first), an integer (the -dimension over which to operate), or a sequence (operate over multiple -dimensions). - -Usage: askew(a, dimension=None) -Returns: skew of vals in a along dimension, returning ZERO where all vals equal -""" - denom = N.power(amoment(a,2,dimension),1.5) - zero = N.equal(denom,0) - if type(denom) == N.ndarray and asum(zero) <> 0: - print "Number of zeros in askew: ",asum(zero) - denom = denom + zero # prevent divide-by-zero - return N.where(zero, 0, amoment(a,3,dimension)/denom) - - - def akurtosis(a,dimension=None): - """ -Returns the kurtosis of a distribution (normal ==> 3.0; >3 means -heavier in the tails, and usually more peaked). Use akurtosistest() -to see if it's close enough. Dimension can equal None (ravel array -first), an integer (the dimension over which to operate), or a -sequence (operate over multiple dimensions). - -Usage: akurtosis(a,dimension=None) -Returns: kurtosis of values in a along dimension, and ZERO where all vals equal -""" - denom = N.power(amoment(a,2,dimension),2) - zero = N.equal(denom,0) - if type(denom) == N.ndarray and asum(zero) <> 0: - print "Number of zeros in akurtosis: ",asum(zero) - denom = denom + zero # prevent divide-by-zero - return N.where(zero,0,amoment(a,4,dimension)/denom) - - - def adescribe(inarray,dimension=None): - """ -Returns several descriptive statistics of the passed array. Dimension -can equal None (ravel array first), an integer (the dimension over -which to operate), or a sequence (operate over multiple dimensions). - -Usage: adescribe(inarray,dimension=None) -Returns: n, (min,max), mean, standard deviation, skew, kurtosis -""" - if dimension == None: - inarray = N.ravel(inarray) - dimension = 0 - n = inarray.shape[dimension] - mm = (N.minimum.reduce(inarray),N.maximum.reduce(inarray)) - m = amean(inarray,dimension) - sd = astdev(inarray,dimension) - skew = askew(inarray,dimension) - kurt = akurtosis(inarray,dimension) - return n, mm, m, sd, skew, kurt - - -##################################### -######## NORMALITY TESTS ########## -##################################### - - def askewtest(a,dimension=None): - """ -Tests whether the skew is significantly different from a normal -distribution. Dimension can equal None (ravel array first), an -integer (the dimension over which to operate), or a sequence (operate -over multiple dimensions). - -Usage: askewtest(a,dimension=None) -Returns: z-score and 2-tail z-probability -""" - if dimension == None: - a = N.ravel(a) - dimension = 0 - b2 = askew(a,dimension) - n = float(a.shape[dimension]) - y = b2 * N.sqrt(((n+1)*(n+3)) / (6.0*(n-2)) ) - beta2 = ( 3.0*(n*n+27*n-70)*(n+1)*(n+3) ) / ( (n-2.0)*(n+5)*(n+7)*(n+9) ) - W2 = -1 + N.sqrt(2*(beta2-1)) - delta = 1/N.sqrt(N.log(N.sqrt(W2))) - alpha = N.sqrt(2/(W2-1)) - y = N.where(y==0,1,y) - Z = delta*N.log(y/alpha + N.sqrt((y/alpha)**2+1)) - return Z, (1.0-zprob(Z))*2 - - - def akurtosistest(a,dimension=None): - """ -Tests whether a dataset has normal kurtosis (i.e., -kurtosis=3(n-1)/(n+1)) Valid only for n>20. Dimension can equal None -(ravel array first), an integer (the dimension over which to operate), -or a sequence (operate over multiple dimensions). - -Usage: akurtosistest(a,dimension=None) -Returns: z-score and 2-tail z-probability, returns 0 for bad pixels -""" - if dimension == None: - a = N.ravel(a) - dimension = 0 - n = float(a.shape[dimension]) - if n<20: - print "akurtosistest only valid for n>=20 ... continuing anyway, n=",n - b2 = akurtosis(a,dimension) - E = 3.0*(n-1) /(n+1) - varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1)*(n+3)*(n+5)) - x = (b2-E)/N.sqrt(varb2) - sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * N.sqrt((6.0*(n+3)*(n+5))/ - (n*(n-2)*(n-3))) - A = 6.0 + 8.0/sqrtbeta1 *(2.0/sqrtbeta1 + N.sqrt(1+4.0/(sqrtbeta1**2))) - term1 = 1 -2/(9.0*A) - denom = 1 +x*N.sqrt(2/(A-4.0)) - denom = N.where(N.less(denom,0), 99, denom) - term2 = N.where(N.equal(denom,0), term1, N.power((1-2.0/A)/denom,1/3.0)) - Z = ( term1 - term2 ) / N.sqrt(2/(9.0*A)) - Z = N.where(N.equal(denom,99), 0, Z) - return Z, (1.0-zprob(Z))*2 - - - def anormaltest(a,dimension=None): - """ -Tests whether skew and/OR kurtosis of dataset differs from normal -curve. Can operate over multiple dimensions. Dimension can equal -None (ravel array first), an integer (the dimension over which to -operate), or a sequence (operate over multiple dimensions). - -Usage: anormaltest(a,dimension=None) -Returns: z-score and 2-tail probability -""" - if dimension == None: - a = N.ravel(a) - dimension = 0 - s,p = askewtest(a,dimension) - k,p = akurtosistest(a,dimension) - k2 = N.power(s,2) + N.power(k,2) - return k2, achisqprob(k2,2) - - -##################################### -###### AFREQUENCY FUNCTIONS ####### -##################################### - - def aitemfreq(a): - """ -Returns a 2D array of item frequencies. Column 1 contains item values, -column 2 contains their respective counts. Assumes a 1D array is passed. -@@@sorting OK? - -Usage: aitemfreq(a) -Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies) -""" - scores = pstat.aunique(a) - scores = N.sort(scores) - freq = N.zeros(len(scores)) - for i in range(len(scores)): - freq[i] = N.add.reduce(N.equal(a,scores[i])) - return N.array(pstat.aabut(scores, freq)) - - - def ascoreatpercentile (inarray, percent): - """ -Usage: ascoreatpercentile(inarray,percent) 0= targetcf: - break - score = binsize * ((targetcf - cumhist[i-1]) / float(h[i])) + (lrl+binsize*i) - return score - - - def apercentileofscore (inarray,score,histbins=10,defaultlimits=None): - """ -Note: result of this function depends on the values used to histogram -the data(!). - -Usage: apercentileofscore(inarray,score,histbins=10,defaultlimits=None) -Returns: percentile-position of score (0-100) relative to inarray -""" - h, lrl, binsize, extras = histogram(inarray,histbins,defaultlimits) - cumhist = cumsum(h*1) - i = int((score - lrl)/float(binsize)) - pct = (cumhist[i-1]+((score-(lrl+binsize*i))/float(binsize))*h[i])/float(len(inarray)) * 100 - return pct - - - def ahistogram (inarray,numbins=10,defaultlimits=None,printextras=1): - """ -Returns (i) an array of histogram bin counts, (ii) the smallest value -of the histogram binning, and (iii) the bin width (the last 2 are not -necessarily integers). Default number of bins is 10. Defaultlimits -can be None (the routine picks bins spanning all the numbers in the -inarray) or a 2-sequence (lowerlimit, upperlimit). Returns all of the -following: array of bin values, lowerreallimit, binsize, extrapoints. - -Usage: ahistogram(inarray,numbins=10,defaultlimits=None,printextras=1) -Returns: (array of bin counts, bin-minimum, min-width, #-points-outside-range) -""" - inarray = N.ravel(inarray) # flatten any >1D arrays - if (defaultlimits <> None): - lowerreallimit = defaultlimits[0] - upperreallimit = defaultlimits[1] - binsize = (upperreallimit-lowerreallimit) / float(numbins) - else: - Min = N.minimum.reduce(inarray) - Max = N.maximum.reduce(inarray) - estbinwidth = float(Max - Min)/float(numbins) + 1e-6 - binsize = (Max-Min+estbinwidth)/float(numbins) - lowerreallimit = Min - binsize/2.0 #lower real limit,1st bin - bins = N.zeros(numbins) - extrapoints = 0 - for num in inarray: - try: - if (num-lowerreallimit) < 0: - extrapoints = extrapoints + 1 - else: - bintoincrement = int((num-lowerreallimit) / float(binsize)) - bins[bintoincrement] = bins[bintoincrement] + 1 - except: # point outside lower/upper limits - extrapoints = extrapoints + 1 - if (extrapoints > 0 and printextras == 1): - print '\nPoints outside given histogram range =',extrapoints - return (bins, lowerreallimit, binsize, extrapoints) - - - def acumfreq(a,numbins=10,defaultreallimits=None): - """ -Returns a cumulative frequency histogram, using the histogram function. -Defaultreallimits can be None (use all data), or a 2-sequence containing -lower and upper limits on values to include. - -Usage: acumfreq(a,numbins=10,defaultreallimits=None) -Returns: array of cumfreq bin values, lowerreallimit, binsize, extrapoints -""" - h,l,b,e = histogram(a,numbins,defaultreallimits) - cumhist = cumsum(h*1) - return cumhist,l,b,e - - - def arelfreq(a,numbins=10,defaultreallimits=None): - """ -Returns a relative frequency histogram, using the histogram function. -Defaultreallimits can be None (use all data), or a 2-sequence containing -lower and upper limits on values to include. - -Usage: arelfreq(a,numbins=10,defaultreallimits=None) -Returns: array of cumfreq bin values, lowerreallimit, binsize, extrapoints -""" - h,l,b,e = histogram(a,numbins,defaultreallimits) - h = N.array(h/float(a.shape[0])) - return h,l,b,e - - -##################################### -###### AVARIABILITY FUNCTIONS ##### -##################################### - - def aobrientransform(*args): - """ -Computes a transform on input data (any number of columns). Used to -test for homogeneity of variance prior to running one-way stats. Each -array in *args is one level of a factor. If an F_oneway() run on the -transformed data and found significant, variances are unequal. From -Maxwell and Delaney, p.112. - -Usage: aobrientransform(*args) *args = 1D arrays, one per level of factor -Returns: transformed data for use in an ANOVA -""" - TINY = 1e-10 - k = len(args) - n = N.zeros(k,N.float_) - v = N.zeros(k,N.float_) - m = N.zeros(k,N.float_) - nargs = [] - for i in range(k): - nargs.append(args[i].astype(N.float_)) - n[i] = float(len(nargs[i])) - v[i] = var(nargs[i]) - m[i] = mean(nargs[i]) - for j in range(k): - for i in range(n[j]): - t1 = (n[j]-1.5)*n[j]*(nargs[j][i]-m[j])**2 - t2 = 0.5*v[j]*(n[j]-1.0) - t3 = (n[j]-1.0)*(n[j]-2.0) - nargs[j][i] = (t1-t2) / float(t3) - check = 1 - for j in range(k): - if v[j] - mean(nargs[j]) > TINY: - check = 0 - if check <> 1: - raise ValueError, 'Lack of convergence in obrientransform.' - else: - return N.array(nargs) - - - def asamplevar (inarray,dimension=None,keepdims=0): - """ -Returns the sample standard deviation of the values in the passed -array (i.e., using N). Dimension can equal None (ravel array first), -an integer (the dimension over which to operate), or a sequence -(operate over multiple dimensions). Set keepdims=1 to return an array -with the same number of dimensions as inarray. - -Usage: asamplevar(inarray,dimension=None,keepdims=0) -""" - if dimension == None: - inarray = N.ravel(inarray) - dimension = 0 - if dimension == 1: - mn = amean(inarray,dimension)[:,N.NewAxis] - else: - mn = amean(inarray,dimension,keepdims=1) - deviations = inarray - mn - if type(dimension) == ListType: - n = 1 - for d in dimension: - n = n*inarray.shape[d] - else: - n = inarray.shape[dimension] - svar = ass(deviations,dimension,keepdims) / float(n) - return svar - - - def asamplestdev (inarray, dimension=None, keepdims=0): - """ -Returns the sample standard deviation of the values in the passed -array (i.e., using N). Dimension can equal None (ravel array first), -an integer (the dimension over which to operate), or a sequence -(operate over multiple dimensions). Set keepdims=1 to return an array -with the same number of dimensions as inarray. - -Usage: asamplestdev(inarray,dimension=None,keepdims=0) -""" - return N.sqrt(asamplevar(inarray,dimension,keepdims)) - - - def asignaltonoise(instack,dimension=0): - """ -Calculates signal-to-noise. Dimension can equal None (ravel array -first), an integer (the dimension over which to operate), or a -sequence (operate over multiple dimensions). - -Usage: asignaltonoise(instack,dimension=0): -Returns: array containing the value of (mean/stdev) along dimension, - or 0 when stdev=0 -""" - m = mean(instack,dimension) - sd = stdev(instack,dimension) - return N.where(sd==0,0,m/sd) - - - def acov (x,y, dimension=None,keepdims=0): - """ -Returns the estimated covariance of the values in the passed -array (i.e., N-1). Dimension can equal None (ravel array first), an -integer (the dimension over which to operate), or a sequence (operate -over multiple dimensions). Set keepdims=1 to return an array with the -same number of dimensions as inarray. - -Usage: acov(x,y,dimension=None,keepdims=0) -""" - if dimension == None: - x = N.ravel(x) - y = N.ravel(y) - dimension = 0 - xmn = amean(x,dimension,1) # keepdims - xdeviations = x - xmn - ymn = amean(y,dimension,1) # keepdims - ydeviations = y - ymn - if type(dimension) == ListType: - n = 1 - for d in dimension: - n = n*x.shape[d] - else: - n = x.shape[dimension] - covar = N.sum(xdeviations*ydeviations)/float(n-1) - return covar - - - def avar (inarray, dimension=None,keepdims=0): - """ -Returns the estimated population variance of the values in the passed -array (i.e., N-1). Dimension can equal None (ravel array first), an -integer (the dimension over which to operate), or a sequence (operate -over multiple dimensions). Set keepdims=1 to return an array with the -same number of dimensions as inarray. - -Usage: avar(inarray,dimension=None,keepdims=0) -""" - if dimension == None: - inarray = N.ravel(inarray) - dimension = 0 - mn = amean(inarray,dimension,1) - deviations = inarray - mn - if type(dimension) == ListType: - n = 1 - for d in dimension: - n = n*inarray.shape[d] - else: - n = inarray.shape[dimension] - var = ass(deviations,dimension,keepdims)/float(n-1) - return var - - - def astdev (inarray, dimension=None, keepdims=0): - """ -Returns the estimated population standard deviation of the values in -the passed array (i.e., N-1). Dimension can equal None (ravel array -first), an integer (the dimension over which to operate), or a -sequence (operate over multiple dimensions). Set keepdims=1 to return -an array with the same number of dimensions as inarray. - -Usage: astdev(inarray,dimension=None,keepdims=0) -""" - return N.sqrt(avar(inarray,dimension,keepdims)) - - - def asterr (inarray, dimension=None, keepdims=0): - """ -Returns the estimated population standard error of the values in the -passed array (i.e., N-1). Dimension can equal None (ravel array -first), an integer (the dimension over which to operate), or a -sequence (operate over multiple dimensions). Set keepdims=1 to return -an array with the same number of dimensions as inarray. - -Usage: asterr(inarray,dimension=None,keepdims=0) -""" - if dimension == None: - inarray = N.ravel(inarray) - dimension = 0 - return astdev(inarray,dimension,keepdims) / float(N.sqrt(inarray.shape[dimension])) - - - def asem (inarray, dimension=None, keepdims=0): - """ -Returns the standard error of the mean (i.e., using N) of the values -in the passed array. Dimension can equal None (ravel array first), an -integer (the dimension over which to operate), or a sequence (operate -over multiple dimensions). Set keepdims=1 to return an array with the -same number of dimensions as inarray. - -Usage: asem(inarray,dimension=None, keepdims=0) -""" - if dimension == None: - inarray = N.ravel(inarray) - dimension = 0 - if type(dimension) == ListType: - n = 1 - for d in dimension: - n = n*inarray.shape[d] - else: - n = inarray.shape[dimension] - s = asamplestdev(inarray,dimension,keepdims) / N.sqrt(n-1) - return s - - - def az (a, score): - """ -Returns the z-score of a given input score, given thearray from which -that score came. Not appropriate for population calculations, nor for -arrays > 1D. - -Usage: az(a, score) -""" - z = (score-amean(a)) / asamplestdev(a) - return z - - - def azs (a): - """ -Returns a 1D array of z-scores, one for each score in the passed array, -computed relative to the passed array. - -Usage: azs(a) -""" - zscores = [] - for item in a: - zscores.append(z(a,item)) - return N.array(zscores) - - - def azmap (scores, compare, dimension=0): - """ -Returns an array of z-scores the shape of scores (e.g., [x,y]), compared to -array passed to compare (e.g., [time,x,y]). Assumes collapsing over dim 0 -of the compare array. - -Usage: azs(scores, compare, dimension=0) -""" - mns = amean(compare,dimension) - sstd = asamplestdev(compare,0) - return (scores - mns) / sstd - - -##################################### -####### ATRIMMING FUNCTIONS ####### -##################################### - -## deleted around() as it's in numpy now - - def athreshold(a,threshmin=None,threshmax=None,newval=0): - """ -Like Numeric.clip() except that values threshmax are replaced -by newval instead of by threshmin/threshmax (respectively). - -Usage: athreshold(a,threshmin=None,threshmax=None,newval=0) -Returns: a, with values threshmax replaced with newval -""" - mask = N.zeros(a.shape) - if threshmin <> None: - mask = mask + N.where(a None: - mask = mask + N.where(a>threshmax,1,0) - mask = N.clip(mask,0,1) - return N.where(mask,newval,a) - - - def atrimboth (a,proportiontocut): - """ -Slices off the passed proportion of items from BOTH ends of the passed -array (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND -'rightmost' 10% of scores. You must pre-sort the array if you want -"proper" trimming. Slices off LESS if proportion results in a -non-integer slice index (i.e., conservatively slices off -proportiontocut). - -Usage: atrimboth (a,proportiontocut) -Returns: trimmed version of array a -""" - lowercut = int(proportiontocut*len(a)) - uppercut = len(a) - lowercut - return a[lowercut:uppercut] - - - def atrim1 (a,proportiontocut,tail='right'): - """ -Slices off the passed proportion of items from ONE end of the passed -array (i.e., if proportiontocut=0.1, slices off 'leftmost' or 'rightmost' -10% of scores). Slices off LESS if proportion results in a non-integer -slice index (i.e., conservatively slices off proportiontocut). - -Usage: atrim1(a,proportiontocut,tail='right') or set tail='left' -Returns: trimmed version of array a -""" - if string.lower(tail) == 'right': - lowercut = 0 - uppercut = len(a) - int(proportiontocut*len(a)) - elif string.lower(tail) == 'left': - lowercut = int(proportiontocut*len(a)) - uppercut = len(a) - return a[lowercut:uppercut] - - -##################################### -##### ACORRELATION FUNCTIONS ###### -##################################### - - def acovariance(X): - """ -Computes the covariance matrix of a matrix X. Requires a 2D matrix input. - -Usage: acovariance(X) -Returns: covariance matrix of X -""" - if len(X.shape) <> 2: - raise TypeError, "acovariance requires 2D matrices" - n = X.shape[0] - mX = amean(X,0) - return N.dot(N.transpose(X),X) / float(n) - N.multiply.outer(mX,mX) - - - def acorrelation(X): - """ -Computes the correlation matrix of a matrix X. Requires a 2D matrix input. - -Usage: acorrelation(X) -Returns: correlation matrix of X -""" - C = acovariance(X) - V = N.diagonal(C) - return C / N.sqrt(N.multiply.outer(V,V)) - - - def apaired(x,y): - """ -Interactively determines the type of data in x and y, and then runs the -appropriated statistic for paired group data. - -Usage: apaired(x,y) x,y = the two arrays of values to be compared -Returns: appropriate statistic name, value, and probability -""" - samples = '' - while samples not in ['i','r','I','R','c','C']: - print '\nIndependent or related samples, or correlation (i,r,c): ', - samples = raw_input() - - if samples in ['i','I','r','R']: - print '\nComparing variances ...', -# USE O'BRIEN'S TEST FOR HOMOGENEITY OF VARIANCE, Maxwell & delaney, p.112 - r = obrientransform(x,y) - f,p = F_oneway(pstat.colex(r,0),pstat.colex(r,1)) - if p<0.05: - vartype='unequal, p='+str(round(p,4)) - else: - vartype='equal' - print vartype - if samples in ['i','I']: - if vartype[0]=='e': - t,p = ttest_ind(x,y,None,0) - print '\nIndependent samples t-test: ', round(t,4),round(p,4) - else: - if len(x)>20 or len(y)>20: - z,p = ranksums(x,y) - print '\nRank Sums test (NONparametric, n>20): ', round(z,4),round(p,4) - else: - u,p = mannwhitneyu(x,y) - print '\nMann-Whitney U-test (NONparametric, ns<20): ', round(u,4),round(p,4) - - else: # RELATED SAMPLES - if vartype[0]=='e': - t,p = ttest_rel(x,y,0) - print '\nRelated samples t-test: ', round(t,4),round(p,4) - else: - t,p = ranksums(x,y) - print '\nWilcoxon T-test (NONparametric): ', round(t,4),round(p,4) - else: # CORRELATION ANALYSIS - corrtype = '' - while corrtype not in ['c','C','r','R','d','D']: - print '\nIs the data Continuous, Ranked, or Dichotomous (c,r,d): ', - corrtype = raw_input() - if corrtype in ['c','C']: - m,b,r,p,see = linregress(x,y) - print '\nLinear regression for continuous variables ...' - lol = [['Slope','Intercept','r','Prob','SEestimate'],[round(m,4),round(b,4),round(r,4),round(p,4),round(see,4)]] - pstat.printcc(lol) - elif corrtype in ['r','R']: - r,p = spearmanr(x,y) - print '\nCorrelation for ranked variables ...' - print "Spearman's r: ",round(r,4),round(p,4) - else: # DICHOTOMOUS - r,p = pointbiserialr(x,y) - print '\nAssuming x contains a dichotomous variable ...' - print 'Point Biserial r: ',round(r,4),round(p,4) - print '\n\n' - return None - - - def dices(x,y): - """ -Calculates Dice's coefficient ... (2*number of common terms)/(number of terms in x + -number of terms in y). Returns a value between 0 (orthogonal) and 1. - -Usage: dices(x,y) -""" - import sets - x = sets.Set(x) - y = sets.Set(y) - common = len(x.intersection(y)) - total = float(len(x) + len(y)) - return 2*common/total - - - def icc(x,y=None,verbose=0): - """ -Calculates intraclass correlation coefficients using simple, Type I sums of squares. -If only one variable is passed, assumed it's an Nx2 matrix - -Usage: icc(x,y=None,verbose=0) -Returns: icc rho, prob ####PROB IS A GUESS BASED ON PEARSON -""" - TINY = 1.0e-20 - if y: - all = N.concatenate([x,y],0) - else: - all = x+0 - x = all[:,0] - y = all[:,1] - totalss = ass(all-mean(all)) - pairmeans = (x+y)/2. - withinss = ass(x-pairmeans) + ass(y-pairmeans) - withindf = float(len(x)) - betwdf = float(len(x)-1) - withinms = withinss / withindf - betweenms = (totalss-withinss) / betwdf - rho = (betweenms-withinms)/(withinms+betweenms) - t = rho*math.sqrt(betwdf/((1.0-rho+TINY)*(1.0+rho+TINY))) - prob = abetai(0.5*betwdf,0.5,betwdf/(betwdf+t*t),verbose) - return rho, prob - - - def alincc(x,y): - """ -Calculates Lin's concordance correlation coefficient. - -Usage: alincc(x,y) where x, y are equal-length arrays -Returns: Lin's CC -""" - x = N.ravel(x) - y = N.ravel(y) - covar = acov(x,y)*(len(x)-1)/float(len(x)) # correct denom to n - xvar = avar(x)*(len(x)-1)/float(len(x)) # correct denom to n - yvar = avar(y)*(len(y)-1)/float(len(y)) # correct denom to n - lincc = (2 * covar) / ((xvar+yvar) +((amean(x)-amean(y))**2)) - return lincc - - - def apearsonr(x,y,verbose=1): - """ -Calculates a Pearson correlation coefficient and returns p. Taken -from Heiman's Basic Statistics for the Behav. Sci (2nd), p.195. - -Usage: apearsonr(x,y,verbose=1) where x,y are equal length arrays -Returns: Pearson's r, two-tailed p-value -""" - TINY = 1.0e-20 - n = len(x) - xmean = amean(x) - ymean = amean(y) - r_num = n*(N.add.reduce(x*y)) - N.add.reduce(x)*N.add.reduce(y) - r_den = math.sqrt((n*ass(x) - asquare_of_sums(x))*(n*ass(y)-asquare_of_sums(y))) - r = (r_num / r_den) - df = n-2 - t = r*math.sqrt(df/((1.0-r+TINY)*(1.0+r+TINY))) - prob = abetai(0.5*df,0.5,df/(df+t*t),verbose) - return r,prob - - - def aspearmanr(x,y): - """ -Calculates a Spearman rank-order correlation coefficient. Taken -from Heiman's Basic Statistics for the Behav. Sci (1st), p.192. - -Usage: aspearmanr(x,y) where x,y are equal-length arrays -Returns: Spearman's r, two-tailed p-value -""" - TINY = 1e-30 - n = len(x) - rankx = rankdata(x) - ranky = rankdata(y) - dsq = N.add.reduce((rankx-ranky)**2) - rs = 1 - 6*dsq / float(n*(n**2-1)) - t = rs * math.sqrt((n-2) / ((rs+1.0)*(1.0-rs))) - df = n-2 - probrs = abetai(0.5*df,0.5,df/(df+t*t)) -# probability values for rs are from part 2 of the spearman function in -# Numerical Recipies, p.510. They close to tables, but not exact.(?) - return rs, probrs - - - def apointbiserialr(x,y): - """ -Calculates a point-biserial correlation coefficient and the associated -probability value. Taken from Heiman's Basic Statistics for the Behav. -Sci (1st), p.194. - -Usage: apointbiserialr(x,y) where x,y are equal length arrays -Returns: Point-biserial r, two-tailed p-value -""" - TINY = 1e-30 - categories = pstat.aunique(x) - data = pstat.aabut(x,y) - if len(categories) <> 2: - raise ValueError, "Exactly 2 categories required (in x) for pointbiserialr()." - else: # there are 2 categories, continue - codemap = pstat.aabut(categories,N.arange(2)) - recoded = pstat.arecode(data,codemap,0) - x = pstat.alinexand(data,0,categories[0]) - y = pstat.alinexand(data,0,categories[1]) - xmean = amean(pstat.acolex(x,1)) - ymean = amean(pstat.acolex(y,1)) - n = len(data) - adjust = math.sqrt((len(x)/float(n))*(len(y)/float(n))) - rpb = (ymean - xmean)/asamplestdev(pstat.acolex(data,1))*adjust - df = n-2 - t = rpb*math.sqrt(df/((1.0-rpb+TINY)*(1.0+rpb+TINY))) - prob = abetai(0.5*df,0.5,df/(df+t*t)) - return rpb, prob - - - def akendalltau(x,y): - """ -Calculates Kendall's tau ... correlation of ordinal data. Adapted -from function kendl1 in Numerical Recipies. Needs good test-cases.@@@ - -Usage: akendalltau(x,y) -Returns: Kendall's tau, two-tailed p-value -""" - n1 = 0 - n2 = 0 - iss = 0 - for j in range(len(x)-1): - for k in range(j,len(y)): - a1 = x[j] - x[k] - a2 = y[j] - y[k] - aa = a1 * a2 - if (aa): # neither array has a tie - n1 = n1 + 1 - n2 = n2 + 1 - if aa > 0: - iss = iss + 1 - else: - iss = iss -1 - else: - if (a1): - n1 = n1 + 1 - else: - n2 = n2 + 1 - tau = iss / math.sqrt(n1*n2) - svar = (4.0*len(x)+10.0) / (9.0*len(x)*(len(x)-1)) - z = tau / math.sqrt(svar) - prob = erfcc(abs(z)/1.4142136) - return tau, prob - - - def alinregress(*args): - """ -Calculates a regression line on two arrays, x and y, corresponding to x,y -pairs. If a single 2D array is passed, alinregress finds dim with 2 levels -and splits data into x,y pairs along that dim. - -Usage: alinregress(*args) args=2 equal-length arrays, or one 2D array -Returns: slope, intercept, r, two-tailed prob, sterr-of-the-estimate, n -""" - TINY = 1.0e-20 - if len(args) == 1: # more than 1D array? - args = args[0] - if len(args) == 2: - x = args[0] - y = args[1] - else: - x = args[:,0] - y = args[:,1] - else: - x = args[0] - y = args[1] - n = len(x) - xmean = amean(x) - ymean = amean(y) - r_num = n*(N.add.reduce(x*y)) - N.add.reduce(x)*N.add.reduce(y) - r_den = math.sqrt((n*ass(x) - asquare_of_sums(x))*(n*ass(y)-asquare_of_sums(y))) - r = r_num / r_den - z = 0.5*math.log((1.0+r+TINY)/(1.0-r+TINY)) - df = n-2 - t = r*math.sqrt(df/((1.0-r+TINY)*(1.0+r+TINY))) - prob = abetai(0.5*df,0.5,df/(df+t*t)) - slope = r_num / (float(n)*ass(x) - asquare_of_sums(x)) - intercept = ymean - slope*xmean - sterrest = math.sqrt(1-r*r)*asamplestdev(y) - return slope, intercept, r, prob, sterrest, n - - def amasslinregress(*args): - """ -Calculates a regression line on one 1D array (x) and one N-D array (y). - -Returns: slope, intercept, r, two-tailed prob, sterr-of-the-estimate, n -""" - TINY = 1.0e-20 - if len(args) == 1: # more than 1D array? - args = args[0] - if len(args) == 2: - x = N.ravel(args[0]) - y = args[1] - else: - x = N.ravel(args[:,0]) - y = args[:,1] - else: - x = args[0] - y = args[1] - x = x.astype(N.float_) - y = y.astype(N.float_) - n = len(x) - xmean = amean(x) - ymean = amean(y,0) - shp = N.ones(len(y.shape)) - shp[0] = len(x) - x.shape = shp - print x.shape, y.shape - r_num = n*(N.add.reduce(x*y,0)) - N.add.reduce(x)*N.add.reduce(y,0) - r_den = N.sqrt((n*ass(x) - asquare_of_sums(x))*(n*ass(y,0)-asquare_of_sums(y,0))) - zerodivproblem = N.equal(r_den,0) - r_den = N.where(zerodivproblem,1,r_den) # avoid zero-division in 1st place - r = r_num / r_den # need to do this nicely for matrix division - r = N.where(zerodivproblem,0.0,r) - z = 0.5*N.log((1.0+r+TINY)/(1.0-r+TINY)) - df = n-2 - t = r*N.sqrt(df/((1.0-r+TINY)*(1.0+r+TINY))) - prob = abetai(0.5*df,0.5,df/(df+t*t)) - - ss = float(n)*ass(x)-asquare_of_sums(x) - s_den = N.where(ss==0,1,ss) # avoid zero-division in 1st place - slope = r_num / s_den - intercept = ymean - slope*xmean - sterrest = N.sqrt(1-r*r)*asamplestdev(y,0) - return slope, intercept, r, prob, sterrest, n - - -##################################### -##### AINFERENTIAL STATISTICS ##### -##################################### - - def attest_1samp(a,popmean,printit=0,name='Sample',writemode='a'): - """ -Calculates the t-obtained for the independent samples T-test on ONE group -of scores a, given a population mean. If printit=1, results are printed -to the screen. If printit='filename', the results are output to 'filename' -using the given writemode (default=append). Returns t-value, and prob. - -Usage: attest_1samp(a,popmean,Name='Sample',printit=0,writemode='a') -Returns: t-value, two-tailed prob -""" - if type(a) != N.ndarray: - a = N.array(a) - x = amean(a) - v = avar(a) - n = len(a) - df = n-1 - svar = ((n-1)*v) / float(df) - t = (x-popmean)/math.sqrt(svar*(1.0/n)) - prob = abetai(0.5*df,0.5,df/(df+t*t)) - - if printit <> 0: - statname = 'Single-sample T-test.' - outputpairedstats(printit,writemode, - 'Population','--',popmean,0,0,0, - name,n,x,v,N.minimum.reduce(N.ravel(a)), - N.maximum.reduce(N.ravel(a)), - statname,t,prob) - return t,prob - - - def attest_ind (a, b, dimension=None, printit=0, name1='Samp1', name2='Samp2',writemode='a'): - """ -Calculates the t-obtained T-test on TWO INDEPENDENT samples of scores -a, and b. From Numerical Recipies, p.483. If printit=1, results are -printed to the screen. If printit='filename', the results are output -to 'filename' using the given writemode (default=append). Dimension -can equal None (ravel array first), or an integer (the dimension over -which to operate on a and b). - -Usage: attest_ind (a,b,dimension=None,printit=0, - Name1='Samp1',Name2='Samp2',writemode='a') -Returns: t-value, two-tailed p-value -""" - if dimension == None: - a = N.ravel(a) - b = N.ravel(b) - dimension = 0 - x1 = amean(a,dimension) - x2 = amean(b,dimension) - v1 = avar(a,dimension) - v2 = avar(b,dimension) - n1 = a.shape[dimension] - n2 = b.shape[dimension] - df = n1+n2-2 - svar = ((n1-1)*v1+(n2-1)*v2) / float(df) - zerodivproblem = N.equal(svar,0) - svar = N.where(zerodivproblem,1,svar) # avoid zero-division in 1st place - t = (x1-x2)/N.sqrt(svar*(1.0/n1 + 1.0/n2)) # N-D COMPUTATION HERE!!!!!! - t = N.where(zerodivproblem,1.0,t) # replace NaN/wrong t-values with 1.0 - probs = abetai(0.5*df,0.5,float(df)/(df+t*t)) - - if type(t) == N.ndarray: - probs = N.reshape(probs,t.shape) - if probs.shape == (1,): - probs = probs[0] - - if printit <> 0: - if type(t) == N.ndarray: - t = t[0] - if type(probs) == N.ndarray: - probs = probs[0] - statname = 'Independent samples T-test.' - outputpairedstats(printit,writemode, - name1,n1,x1,v1,N.minimum.reduce(N.ravel(a)), - N.maximum.reduce(N.ravel(a)), - name2,n2,x2,v2,N.minimum.reduce(N.ravel(b)), - N.maximum.reduce(N.ravel(b)), - statname,t,probs) - return - return t, probs - - def ap2t(pval,df): - """ -Tries to compute a t-value from a p-value (or pval array) and associated df. -SLOW for large numbers of elements(!) as it re-computes p-values 20 times -(smaller step-sizes) at which point it decides it's done. Keeps the signs -of the input array. Returns 1000 (or -1000) if t>100. - -Usage: ap2t(pval,df) -Returns: an array of t-values with the shape of pval - """ - pval = N.array(pval) - signs = N.sign(pval) - pval = abs(pval) - t = N.ones(pval.shape,N.float_)*50 - step = N.ones(pval.shape,N.float_)*25 - print "Initial ap2t() prob calc" - prob = abetai(0.5*df,0.5,float(df)/(df+t*t)) - print 'ap2t() iter: ', - for i in range(10): - print i,' ', - t = N.where(pval99.9,1000,t) # hit upper-boundary - t = t+signs - return t #, prob, pval - - - def attest_rel (a,b,dimension=None,printit=0,name1='Samp1',name2='Samp2',writemode='a'): - """ -Calculates the t-obtained T-test on TWO RELATED samples of scores, a -and b. From Numerical Recipies, p.483. If printit=1, results are -printed to the screen. If printit='filename', the results are output -to 'filename' using the given writemode (default=append). Dimension -can equal None (ravel array first), or an integer (the dimension over -which to operate on a and b). - -Usage: attest_rel(a,b,dimension=None,printit=0, - name1='Samp1',name2='Samp2',writemode='a') -Returns: t-value, two-tailed p-value -""" - if dimension == None: - a = N.ravel(a) - b = N.ravel(b) - dimension = 0 - if len(a)<>len(b): - raise ValueError, 'Unequal length arrays.' - x1 = amean(a,dimension) - x2 = amean(b,dimension) - v1 = avar(a,dimension) - v2 = avar(b,dimension) - n = a.shape[dimension] - df = float(n-1) - d = (a-b).astype('d') - - denom = N.sqrt((n*N.add.reduce(d*d,dimension) - N.add.reduce(d,dimension)**2) /df) - zerodivproblem = N.equal(denom,0) - denom = N.where(zerodivproblem,1,denom) # avoid zero-division in 1st place - t = N.add.reduce(d,dimension) / denom # N-D COMPUTATION HERE!!!!!! - t = N.where(zerodivproblem,1.0,t) # replace NaN/wrong t-values with 1.0 - probs = abetai(0.5*df,0.5,float(df)/(df+t*t)) - if type(t) == N.ndarray: - probs = N.reshape(probs,t.shape) - if probs.shape == (1,): - probs = probs[0] - - if printit <> 0: - statname = 'Related samples T-test.' - outputpairedstats(printit,writemode, - name1,n,x1,v1,N.minimum.reduce(N.ravel(a)), - N.maximum.reduce(N.ravel(a)), - name2,n,x2,v2,N.minimum.reduce(N.ravel(b)), - N.maximum.reduce(N.ravel(b)), - statname,t,probs) - return - return t, probs - - - def achisquare(f_obs,f_exp=None): - """ -Calculates a one-way chi square for array of observed frequencies and returns -the result. If no expected frequencies are given, the total N is assumed to -be equally distributed across all groups. -@@@NOT RIGHT?? - -Usage: achisquare(f_obs, f_exp=None) f_obs = array of observed cell freq. -Returns: chisquare-statistic, associated p-value -""" - - k = len(f_obs) - if f_exp == None: - f_exp = N.array([sum(f_obs)/float(k)] * len(f_obs),N.float_) - f_exp = f_exp.astype(N.float_) - chisq = N.add.reduce((f_obs-f_exp)**2 / f_exp) - return chisq, achisqprob(chisq, k-1) - - - def aks_2samp (data1,data2): - """ -Computes the Kolmogorov-Smirnof statistic on 2 samples. Modified from -Numerical Recipies in C, page 493. Returns KS D-value, prob. Not ufunc- -like. - -Usage: aks_2samp(data1,data2) where data1 and data2 are 1D arrays -Returns: KS D-value, p-value -""" - j1 = 0 # N.zeros(data1.shape[1:]) TRIED TO MAKE THIS UFUNC-LIKE - j2 = 0 # N.zeros(data2.shape[1:]) - fn1 = 0.0 # N.zeros(data1.shape[1:],N.float_) - fn2 = 0.0 # N.zeros(data2.shape[1:],N.float_) - n1 = data1.shape[0] - n2 = data2.shape[0] - en1 = n1*1 - en2 = n2*1 - d = N.zeros(data1.shape[1:],N.float_) - data1 = N.sort(data1,0) - data2 = N.sort(data2,0) - while j1 < n1 and j2 < n2: - d1=data1[j1] - d2=data2[j2] - if d1 <= d2: - fn1 = (j1)/float(en1) - j1 = j1 + 1 - if d2 <= d1: - fn2 = (j2)/float(en2) - j2 = j2 + 1 - dt = (fn2-fn1) - if abs(dt) > abs(d): - d = dt -# try: - en = math.sqrt(en1*en2/float(en1+en2)) - prob = aksprob((en+0.12+0.11/en)*N.fabs(d)) -# except: -# prob = 1.0 - return d, prob - - - def amannwhitneyu(x,y): - """ -Calculates a Mann-Whitney U statistic on the provided scores and -returns the result. Use only when the n in each condition is < 20 and -you have 2 independent samples of ranks. REMEMBER: Mann-Whitney U is -significant if the u-obtained is LESS THAN or equal to the critical -value of U. - -Usage: amannwhitneyu(x,y) where x,y are arrays of values for 2 conditions -Returns: u-statistic, one-tailed p-value (i.e., p(z(U))) -""" - n1 = len(x) - n2 = len(y) - ranked = rankdata(N.concatenate((x,y))) - rankx = ranked[0:n1] # get the x-ranks - ranky = ranked[n1:] # the rest are y-ranks - u1 = n1*n2 + (n1*(n1+1))/2.0 - sum(rankx) # calc U for x - u2 = n1*n2 - u1 # remainder is U for y - bigu = max(u1,u2) - smallu = min(u1,u2) - T = math.sqrt(tiecorrect(ranked)) # correction factor for tied scores - if T == 0: - raise ValueError, 'All numbers are identical in amannwhitneyu' - sd = math.sqrt(T*n1*n2*(n1+n2+1)/12.0) - z = abs((bigu-n1*n2/2.0) / sd) # normal approximation for prob calc - return smallu, 1.0 - azprob(z) - - - def atiecorrect(rankvals): - """ -Tie-corrector for ties in Mann Whitney U and Kruskal Wallis H tests. -See Siegel, S. (1956) Nonparametric Statistics for the Behavioral -Sciences. New York: McGraw-Hill. Code adapted from |Stat rankind.c -code. - -Usage: atiecorrect(rankvals) -Returns: T correction factor for U or H -""" - sorted,posn = ashellsort(N.array(rankvals)) - n = len(sorted) - T = 0.0 - i = 0 - while (i len(y): - raise ValueError, 'Unequal N in awilcoxont. Aborting.' - d = x-y - d = N.compress(N.not_equal(d,0),d) # Keep all non-zero differences - count = len(d) - absd = abs(d) - absranked = arankdata(absd) - r_plus = 0.0 - r_minus = 0.0 - for i in range(len(absd)): - if d[i] < 0: - r_minus = r_minus + absranked[i] - else: - r_plus = r_plus + absranked[i] - wt = min(r_plus, r_minus) - mn = count * (count+1) * 0.25 - se = math.sqrt(count*(count+1)*(2.0*count+1.0)/24.0) - z = math.fabs(wt-mn) / se - z = math.fabs(wt-mn) / se - prob = 2*(1.0 -zprob(abs(z))) - return wt, prob - - - def akruskalwallish(*args): - """ -The Kruskal-Wallis H-test is a non-parametric ANOVA for 3 or more -groups, requiring at least 5 subjects in each group. This function -calculates the Kruskal-Wallis H and associated p-value for 3 or more -independent samples. - -Usage: akruskalwallish(*args) args are separate arrays for 3+ conditions -Returns: H-statistic (corrected for ties), associated p-value -""" - assert len(args) == 3, "Need at least 3 groups in stats.akruskalwallish()" - args = list(args) - n = [0]*len(args) - n = map(len,args) - all = [] - for i in range(len(args)): - all = all + args[i].tolist() - ranked = rankdata(all) - T = tiecorrect(ranked) - for i in range(len(args)): - args[i] = ranked[0:n[i]] - del ranked[0:n[i]] - rsums = [] - for i in range(len(args)): - rsums.append(sum(args[i])**2) - rsums[i] = rsums[i] / float(n[i]) - ssbn = sum(rsums) - totaln = sum(n) - h = 12.0 / (totaln*(totaln+1)) * ssbn - 3*(totaln+1) - df = len(args) - 1 - if T == 0: - raise ValueError, 'All numbers are identical in akruskalwallish' - h = h / float(T) - return h, chisqprob(h,df) - - - def afriedmanchisquare(*args): - """ -Friedman Chi-Square is a non-parametric, one-way within-subjects -ANOVA. This function calculates the Friedman Chi-square test for -repeated measures and returns the result, along with the associated -probability value. It assumes 3 or more repeated measures. Only 3 -levels requires a minimum of 10 subjects in the study. Four levels -requires 5 subjects per level(??). - -Usage: afriedmanchisquare(*args) args are separate arrays for 2+ conditions -Returns: chi-square statistic, associated p-value -""" - k = len(args) - if k < 3: - raise ValueError, '\nLess than 3 levels. Friedman test not appropriate.\n' - n = len(args[0]) - data = apply(pstat.aabut,args) - data = data.astype(N.float_) - for i in range(len(data)): - data[i] = arankdata(data[i]) - ssbn = asum(asum(args,1)**2) - chisq = 12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1) - return chisq, achisqprob(chisq,k-1) - - -##################################### -#### APROBABILITY CALCULATIONS #### -##################################### - - def achisqprob(chisq,df): - """ -Returns the (1-tail) probability value associated with the provided chi-square -value and df. Heavily modified from chisq.c in Gary Perlman's |Stat. Can -handle multiple dimensions. - -Usage: achisqprob(chisq,df) chisq=chisquare stat., df=degrees of freedom -""" - BIG = 200.0 - def ex(x): - BIG = 200.0 - exponents = N.where(N.less(x,-BIG),-BIG,x) - return N.exp(exponents) - - if type(chisq) == N.ndarray: - arrayflag = 1 - else: - arrayflag = 0 - chisq = N.array([chisq]) - if df < 1: - return N.ones(chisq.shape,N.float) - probs = N.zeros(chisq.shape,N.float_) - probs = N.where(N.less_equal(chisq,0),1.0,probs) # set prob=1 for chisq<0 - a = 0.5 * chisq - if df > 1: - y = ex(-a) - if df%2 == 0: - even = 1 - s = y*1 - s2 = s*1 - else: - even = 0 - s = 2.0 * azprob(-N.sqrt(chisq)) - s2 = s*1 - if (df > 2): - chisq = 0.5 * (df - 1.0) - if even: - z = N.ones(probs.shape,N.float_) - else: - z = 0.5 *N.ones(probs.shape,N.float_) - if even: - e = N.zeros(probs.shape,N.float_) - else: - e = N.log(N.sqrt(N.pi)) *N.ones(probs.shape,N.float_) - c = N.log(a) - mask = N.zeros(probs.shape) - a_big = N.greater(a,BIG) - a_big_frozen = -1 *N.ones(probs.shape,N.float_) - totalelements = N.multiply.reduce(N.array(probs.shape)) - while asum(mask)<>totalelements: - e = N.log(z) + e - s = s + ex(c*z-a-e) - z = z + 1.0 -# print z, e, s - newmask = N.greater(z,chisq) - a_big_frozen = N.where(newmask*N.equal(mask,0)*a_big, s, a_big_frozen) - mask = N.clip(newmask+mask,0,1) - if even: - z = N.ones(probs.shape,N.float_) - e = N.ones(probs.shape,N.float_) - else: - z = 0.5 *N.ones(probs.shape,N.float_) - e = 1.0 / N.sqrt(N.pi) / N.sqrt(a) * N.ones(probs.shape,N.float_) - c = 0.0 - mask = N.zeros(probs.shape) - a_notbig_frozen = -1 *N.ones(probs.shape,N.float_) - while asum(mask)<>totalelements: - e = e * (a/z.astype(N.float_)) - c = c + e - z = z + 1.0 -# print '#2', z, e, c, s, c*y+s2 - newmask = N.greater(z,chisq) - a_notbig_frozen = N.where(newmask*N.equal(mask,0)*(1-a_big), - c*y+s2, a_notbig_frozen) - mask = N.clip(newmask+mask,0,1) - probs = N.where(N.equal(probs,1),1, - N.where(N.greater(a,BIG),a_big_frozen,a_notbig_frozen)) - return probs - else: - return s - - - def aerfcc(x): - """ -Returns the complementary error function erfc(x) with fractional error -everywhere less than 1.2e-7. Adapted from Numerical Recipies. Can -handle multiple dimensions. - -Usage: aerfcc(x) -""" - z = abs(x) - t = 1.0 / (1.0+0.5*z) - ans = t * N.exp(-z*z-1.26551223 + t*(1.00002368+t*(0.37409196+t*(0.09678418+t*(-0.18628806+t*(0.27886807+t*(-1.13520398+t*(1.48851587+t*(-0.82215223+t*0.17087277))))))))) - return N.where(N.greater_equal(x,0), ans, 2.0-ans) - - - def azprob(z): - """ -Returns the area under the normal curve 'to the left of' the given z value. -Thus, - for z<0, zprob(z) = 1-tail probability - for z>0, 1.0-zprob(z) = 1-tail probability - for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability -Adapted from z.c in Gary Perlman's |Stat. Can handle multiple dimensions. - -Usage: azprob(z) where z is a z-value -""" - def yfunc(y): - x = (((((((((((((-0.000045255659 * y - +0.000152529290) * y -0.000019538132) * y - -0.000676904986) * y +0.001390604284) * y - -0.000794620820) * y -0.002034254874) * y - +0.006549791214) * y -0.010557625006) * y - +0.011630447319) * y -0.009279453341) * y - +0.005353579108) * y -0.002141268741) * y - +0.000535310849) * y +0.999936657524 - return x - - def wfunc(w): - x = ((((((((0.000124818987 * w - -0.001075204047) * w +0.005198775019) * w - -0.019198292004) * w +0.059054035642) * w - -0.151968751364) * w +0.319152932694) * w - -0.531923007300) * w +0.797884560593) * N.sqrt(w) * 2.0 - return x - - Z_MAX = 6.0 # maximum meaningful z-value - x = N.zeros(z.shape,N.float_) # initialize - y = 0.5 * N.fabs(z) - x = N.where(N.less(y,1.0),wfunc(y*y),yfunc(y-2.0)) # get x's - x = N.where(N.greater(y,Z_MAX*0.5),1.0,x) # kill those with big Z - prob = N.where(N.greater(z,0),(x+1)*0.5,(1-x)*0.5) - return prob - - - def aksprob(alam): - """ -Returns the probability value for a K-S statistic computed via ks_2samp. -Adapted from Numerical Recipies. Can handle multiple dimensions. - -Usage: aksprob(alam) -""" - if type(alam) == N.ndarray: - frozen = -1 *N.ones(alam.shape,N.float64) - alam = alam.astype(N.float64) - arrayflag = 1 - else: - frozen = N.array(-1.) - alam = N.array(alam,N.float64) - arrayflag = 1 - mask = N.zeros(alam.shape) - fac = 2.0 *N.ones(alam.shape,N.float_) - sum = N.zeros(alam.shape,N.float_) - termbf = N.zeros(alam.shape,N.float_) - a2 = N.array(-2.0*alam*alam,N.float64) - totalelements = N.multiply.reduce(N.array(mask.shape)) - for j in range(1,201): - if asum(mask) == totalelements: - break - exponents = (a2*j*j) - overflowmask = N.less(exponents,-746) - frozen = N.where(overflowmask,0,frozen) - mask = mask+overflowmask - term = fac*N.exp(exponents) - sum = sum + term - newmask = N.where(N.less_equal(abs(term),(0.001*termbf)) + - N.less(abs(term),1.0e-8*sum), 1, 0) - frozen = N.where(newmask*N.equal(mask,0), sum, frozen) - mask = N.clip(mask+newmask,0,1) - fac = -fac - termbf = abs(term) - if arrayflag: - return N.where(N.equal(frozen,-1), 1.0, frozen) # 1.0 if doesn't converge - else: - return N.where(N.equal(frozen,-1), 1.0, frozen)[0] # 1.0 if doesn't converge - - - def afprob (dfnum, dfden, F): - """ -Returns the 1-tailed significance level (p-value) of an F statistic -given the degrees of freedom for the numerator (dfR-dfF) and the degrees -of freedom for the denominator (dfF). Can handle multiple dims for F. - -Usage: afprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn -""" - if type(F) == N.ndarray: - return abetai(0.5*dfden, 0.5*dfnum, dfden/(1.0*dfden+dfnum*F)) - else: - return abetai(0.5*dfden, 0.5*dfnum, dfden/float(dfden+dfnum*F)) - - - def abetacf(a,b,x,verbose=1): - """ -Evaluates the continued fraction form of the incomplete Beta function, -betai. (Adapted from: Numerical Recipies in C.) Can handle multiple -dimensions for x. - -Usage: abetacf(a,b,x,verbose=1) -""" - ITMAX = 200 - EPS = 3.0e-7 - - arrayflag = 1 - if type(x) == N.ndarray: - frozen = N.ones(x.shape,N.float_) *-1 #start out w/ -1s, should replace all - else: - arrayflag = 0 - frozen = N.array([-1]) - x = N.array([x]) - mask = N.zeros(x.shape) - bm = az = am = 1.0 - qab = a+b - qap = a+1.0 - qam = a-1.0 - bz = 1.0-qab*x/qap - for i in range(ITMAX+1): - if N.sum(N.ravel(N.equal(frozen,-1)))==0: - break - em = float(i+1) - tem = em + em - d = em*(b-em)*x/((qam+tem)*(a+tem)) - ap = az + d*am - bp = bz+d*bm - d = -(a+em)*(qab+em)*x/((qap+tem)*(a+tem)) - app = ap+d*az - bpp = bp+d*bz - aold = az*1 - am = ap/bpp - bm = bp/bpp - az = app/bpp - bz = 1.0 - newmask = N.less(abs(az-aold),EPS*abs(az)) - frozen = N.where(newmask*N.equal(mask,0), az, frozen) - mask = N.clip(mask+newmask,0,1) - noconverge = asum(N.equal(frozen,-1)) - if noconverge <> 0 and verbose: - print 'a or b too big, or ITMAX too small in Betacf for ',noconverge,' elements' - if arrayflag: - return frozen - else: - return frozen[0] - - - def agammln(xx): - """ -Returns the gamma function of xx. - Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt. -Adapted from: Numerical Recipies in C. Can handle multiple dims ... but -probably doesn't normally have to. - -Usage: agammln(xx) -""" - coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516, - 0.120858003e-2, -0.536382e-5] - x = xx - 1.0 - tmp = x + 5.5 - tmp = tmp - (x+0.5)*N.log(tmp) - ser = 1.0 - for j in range(len(coeff)): - x = x + 1 - ser = ser + coeff[j]/x - return -tmp + N.log(2.50662827465*ser) - - - def abetai(a,b,x,verbose=1): - """ -Returns the incomplete beta function: - - I-sub-x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt) - -where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma -function of a. The continued fraction formulation is implemented -here, using the betacf function. (Adapted from: Numerical Recipies in -C.) Can handle multiple dimensions. - -Usage: abetai(a,b,x,verbose=1) -""" - TINY = 1e-15 - if type(a) == N.ndarray: - if asum(N.less(x,0)+N.greater(x,1)) <> 0: - raise ValueError, 'Bad x in abetai' - x = N.where(N.equal(x,0),TINY,x) - x = N.where(N.equal(x,1.0),1-TINY,x) - - bt = N.where(N.equal(x,0)+N.equal(x,1), 0, -1) - exponents = ( gammln(a+b)-gammln(a)-gammln(b)+a*N.log(x)+b* - N.log(1.0-x) ) - # 746 (below) is the MAX POSSIBLE BEFORE OVERFLOW - exponents = N.where(N.less(exponents,-740),-740,exponents) - bt = N.exp(exponents) - if type(x) == N.ndarray: - ans = N.where(N.less(x,(a+1)/(a+b+2.0)), - bt*abetacf(a,b,x,verbose)/float(a), - 1.0-bt*abetacf(b,a,1.0-x,verbose)/float(b)) - else: - if x<(a+1)/(a+b+2.0): - ans = bt*abetacf(a,b,x,verbose)/float(a) - else: - ans = 1.0-bt*abetacf(b,a,1.0-x,verbose)/float(b) - return ans - - -##################################### -####### AANOVA CALCULATIONS ####### -##################################### - - import LinearAlgebra, operator - LA = LinearAlgebra - - def aglm(data,para): - """ -Calculates a linear model fit ... anova/ancova/lin-regress/t-test/etc. Taken -from: - Peterson et al. Statistical limitations in functional neuroimaging - I. Non-inferential methods and statistical models. Phil Trans Royal Soc - Lond B 354: 1239-1260. - -Usage: aglm(data,para) -Returns: statistic, p-value ??? -""" - if len(para) <> len(data): - print "data and para must be same length in aglm" - return - n = len(para) - p = pstat.aunique(para) - x = N.zeros((n,len(p))) # design matrix - for l in range(len(p)): - x[:,l] = N.equal(para,p[l]) - b = N.dot(N.dot(LA.inv(N.dot(N.transpose(x),x)), # i.e., b=inv(X'X)X'Y - N.transpose(x)), - data) - diffs = (data - N.dot(x,b)) - s_sq = 1./(n-len(p)) * N.dot(N.transpose(diffs), diffs) - - if len(p) == 2: # ttest_ind - c = N.array([1,-1]) - df = n-2 - fact = asum(1.0/asum(x,0)) # i.e., 1/n1 + 1/n2 + 1/n3 ... - t = N.dot(c,b) / N.sqrt(s_sq*fact) - probs = abetai(0.5*df,0.5,float(df)/(df+t*t)) - return t, probs - - - def aF_oneway(*args): - """ -Performs a 1-way ANOVA, returning an F-value and probability given -any number of groups. From Heiman, pp.394-7. - -Usage: aF_oneway (*args) where *args is 2 or more arrays, one per - treatment group -Returns: f-value, probability -""" - na = len(args) # ANOVA on 'na' groups, each in it's own array - means = [0]*na - vars = [0]*na - ns = [0]*na - alldata = [] - tmp = map(N.array,args) - means = map(amean,tmp) - vars = map(avar,tmp) - ns = map(len,args) - alldata = N.concatenate(args) - bign = len(alldata) - sstot = ass(alldata)-(asquare_of_sums(alldata)/float(bign)) - ssbn = 0 - for a in args: - ssbn = ssbn + asquare_of_sums(N.array(a))/float(len(a)) - ssbn = ssbn - (asquare_of_sums(alldata)/float(bign)) - sswn = sstot-ssbn - dfbn = na-1 - dfwn = bign - na - msb = ssbn/float(dfbn) - msw = sswn/float(dfwn) - f = msb/msw - prob = fprob(dfbn,dfwn,f) - return f, prob - - - def aF_value (ER,EF,dfR,dfF): - """ -Returns an F-statistic given the following: - ER = error associated with the null hypothesis (the Restricted model) - EF = error associated with the alternate hypothesis (the Full model) - dfR = degrees of freedom the Restricted model - dfF = degrees of freedom associated with the Restricted model -""" - return ((ER-EF)/float(dfR-dfF) / (EF/float(dfF))) - - - def outputfstats(Enum, Eden, dfnum, dfden, f, prob): - Enum = round(Enum,3) - Eden = round(Eden,3) - dfnum = round(Enum,3) - dfden = round(dfden,3) - f = round(f,3) - prob = round(prob,3) - suffix = '' # for *s after the p-value - if prob < 0.001: suffix = ' ***' - elif prob < 0.01: suffix = ' **' - elif prob < 0.05: suffix = ' *' - title = [['EF/ER','DF','Mean Square','F-value','prob','']] - lofl = title+[[Enum, dfnum, round(Enum/float(dfnum),3), f, prob, suffix], - [Eden, dfden, round(Eden/float(dfden),3),'','','']] - pstat.printcc(lofl) - return - - - def F_value_multivariate(ER, EF, dfnum, dfden): - """ -Returns an F-statistic given the following: - ER = error associated with the null hypothesis (the Restricted model) - EF = error associated with the alternate hypothesis (the Full model) - dfR = degrees of freedom the Restricted model - dfF = degrees of freedom associated with the Restricted model -where ER and EF are matrices from a multivariate F calculation. -""" - if type(ER) in [IntType, FloatType]: - ER = N.array([[ER]]) - if type(EF) in [IntType, FloatType]: - EF = N.array([[EF]]) - n_um = (LA.det(ER) - LA.det(EF)) / float(dfnum) - d_en = LA.det(EF) / float(dfden) - return n_um / d_en - - -##################################### -####### ASUPPORT FUNCTIONS ######## -##################################### - - def asign(a): - """ -Usage: asign(a) -Returns: array shape of a, with -1 where a<0 and +1 where a>=0 -""" - a = N.asarray(a) - if ((type(a) == type(1.4)) or (type(a) == type(1))): - return a-a-N.less(a,0)+N.greater(a,0) - else: - return N.zeros(N.shape(a))-N.less(a,0)+N.greater(a,0) - - - def asum (a, dimension=None,keepdims=0): - """ -An alternative to the Numeric.add.reduce function, which allows one to -(1) collapse over multiple dimensions at once, and/or (2) to retain -all dimensions in the original array (squashing one down to size. -Dimension can equal None (ravel array first), an integer (the -dimension over which to operate), or a sequence (operate over multiple -dimensions). If keepdims=1, the resulting array will have as many -dimensions as the input array. - -Usage: asum(a, dimension=None, keepdims=0) -Returns: array summed along 'dimension'(s), same _number_ of dims if keepdims=1 -""" - if type(a) == N.ndarray and a.dtype in [N.int_, N.short, N.ubyte]: - a = a.astype(N.float_) - if dimension == None: - s = N.sum(N.ravel(a)) - elif type(dimension) in [IntType,FloatType]: - s = N.add.reduce(a, dimension) - if keepdims == 1: - shp = list(a.shape) - shp[dimension] = 1 - s = N.reshape(s,shp) - else: # must be a SEQUENCE of dims to sum over - dims = list(dimension) - dims.sort() - dims.reverse() - s = a *1.0 - for dim in dims: - s = N.add.reduce(s,dim) - if keepdims == 1: - shp = list(a.shape) - for dim in dims: - shp[dim] = 1 - s = N.reshape(s,shp) - return s - - - def acumsum (a,dimension=None): - """ -Returns an array consisting of the cumulative sum of the items in the -passed array. Dimension can equal None (ravel array first), an -integer (the dimension over which to operate), or a sequence (operate -over multiple dimensions, but this last one just barely makes sense). - -Usage: acumsum(a,dimension=None) -""" - if dimension == None: - a = N.ravel(a) - dimension = 0 - if type(dimension) in [ListType, TupleType, N.ndarray]: - dimension = list(dimension) - dimension.sort() - dimension.reverse() - for d in dimension: - a = N.add.accumulate(a,d) - return a - else: - return N.add.accumulate(a,dimension) - - - def ass(inarray, dimension=None, keepdims=0): - """ -Squares each value in the passed array, adds these squares & returns -the result. Unfortunate function name. :-) Defaults to ALL values in -the array. Dimension can equal None (ravel array first), an integer -(the dimension over which to operate), or a sequence (operate over -multiple dimensions). Set keepdims=1 to maintain the original number -of dimensions. - -Usage: ass(inarray, dimension=None, keepdims=0) -Returns: sum-along-'dimension' for (inarray*inarray) -""" - if dimension == None: - inarray = N.ravel(inarray) - dimension = 0 - return asum(inarray*inarray,dimension,keepdims) - - - def asummult (array1,array2,dimension=None,keepdims=0): - """ -Multiplies elements in array1 and array2, element by element, and -returns the sum (along 'dimension') of all resulting multiplications. -Dimension can equal None (ravel array first), an integer (the -dimension over which to operate), or a sequence (operate over multiple -dimensions). A trivial function, but included for completeness. - -Usage: asummult(array1,array2,dimension=None,keepdims=0) -""" - if dimension == None: - array1 = N.ravel(array1) - array2 = N.ravel(array2) - dimension = 0 - return asum(array1*array2,dimension,keepdims) - - - def asquare_of_sums(inarray, dimension=None, keepdims=0): - """ -Adds the values in the passed array, squares that sum, and returns the -result. Dimension can equal None (ravel array first), an integer (the -dimension over which to operate), or a sequence (operate over multiple -dimensions). If keepdims=1, the returned array will have the same -NUMBER of dimensions as the original. - -Usage: asquare_of_sums(inarray, dimension=None, keepdims=0) -Returns: the square of the sum over dim(s) in dimension -""" - if dimension == None: - inarray = N.ravel(inarray) - dimension = 0 - s = asum(inarray,dimension,keepdims) - if type(s) == N.ndarray: - return s.astype(N.float_)*s - else: - return float(s)*s - - - def asumdiffsquared(a,b, dimension=None, keepdims=0): - """ -Takes pairwise differences of the values in arrays a and b, squares -these differences, and returns the sum of these squares. Dimension -can equal None (ravel array first), an integer (the dimension over -which to operate), or a sequence (operate over multiple dimensions). -keepdims=1 means the return shape = len(a.shape) = len(b.shape) - -Usage: asumdiffsquared(a,b) -Returns: sum[ravel(a-b)**2] -""" - if dimension == None: - inarray = N.ravel(a) - dimension = 0 - return asum((a-b)**2,dimension,keepdims) - - - def ashellsort(inarray): - """ -Shellsort algorithm. Sorts a 1D-array. - -Usage: ashellsort(inarray) -Returns: sorted-inarray, sorting-index-vector (for original array) -""" - n = len(inarray) - svec = inarray *1.0 - ivec = range(n) - gap = n/2 # integer division needed - while gap >0: - for i in range(gap,n): - for j in range(i-gap,-1,-gap): - while j>=0 and svec[j]>svec[j+gap]: - temp = svec[j] - svec[j] = svec[j+gap] - svec[j+gap] = temp - itemp = ivec[j] - ivec[j] = ivec[j+gap] - ivec[j+gap] = itemp - gap = gap / 2 # integer division needed -# svec is now sorted input vector, ivec has the order svec[i] = vec[ivec[i]] - return svec, ivec - - - def arankdata(inarray): - """ -Ranks the data in inarray, dealing with ties appropritely. Assumes -a 1D inarray. Adapted from Gary Perlman's |Stat ranksort. - -Usage: arankdata(inarray) -Returns: array of length equal to inarray, containing rank scores -""" - n = len(inarray) - svec, ivec = ashellsort(inarray) - sumranks = 0 - dupcount = 0 - newarray = N.zeros(n,N.float_) - for i in range(n): - sumranks = sumranks + i - dupcount = dupcount + 1 - if i==n-1 or svec[i] <> svec[i+1]: - averank = sumranks / float(dupcount) + 1 - for j in range(i-dupcount+1,i+1): - newarray[ivec[j]] = averank - sumranks = 0 - dupcount = 0 - return newarray - - - def afindwithin(data): - """ -Returns a binary vector, 1=within-subject factor, 0=between. Input -equals the entire data array (i.e., column 1=random factor, last -column = measured values. - -Usage: afindwithin(data) data in |Stat format -""" - numfact = len(data[0])-2 - withinvec = [0]*numfact - for col in range(1,numfact+1): - rows = pstat.linexand(data,col,pstat.unique(pstat.colex(data,1))[0]) # get 1 level of this factor - if len(pstat.unique(pstat.colex(rows,0))) < len(rows): # if fewer subjects than scores on this factor - withinvec[col-1] = 1 - return withinvec - - - ######################################################### - ######################################################### - ###### RE-DEFINE DISPATCHES TO INCLUDE ARRAYS ######### - ######################################################### - ######################################################### - -## CENTRAL TENDENCY: - geometricmean = Dispatch ( (lgeometricmean, (ListType, TupleType)), - (ageometricmean, (N.ndarray,)) ) - harmonicmean = Dispatch ( (lharmonicmean, (ListType, TupleType)), - (aharmonicmean, (N.ndarray,)) ) - mean = Dispatch ( (lmean, (ListType, TupleType)), - (amean, (N.ndarray,)) ) - median = Dispatch ( (lmedian, (ListType, TupleType)), - (amedian, (N.ndarray,)) ) - medianscore = Dispatch ( (lmedianscore, (ListType, TupleType)), - (amedianscore, (N.ndarray,)) ) - mode = Dispatch ( (lmode, (ListType, TupleType)), - (amode, (N.ndarray,)) ) - tmean = Dispatch ( (atmean, (N.ndarray,)) ) - tvar = Dispatch ( (atvar, (N.ndarray,)) ) - tstdev = Dispatch ( (atstdev, (N.ndarray,)) ) - tsem = Dispatch ( (atsem, (N.ndarray,)) ) - -## VARIATION: - moment = Dispatch ( (lmoment, (ListType, TupleType)), - (amoment, (N.ndarray,)) ) - variation = Dispatch ( (lvariation, (ListType, TupleType)), - (avariation, (N.ndarray,)) ) - skew = Dispatch ( (lskew, (ListType, TupleType)), - (askew, (N.ndarray,)) ) - kurtosis = Dispatch ( (lkurtosis, (ListType, TupleType)), - (akurtosis, (N.ndarray,)) ) - describe = Dispatch ( (ldescribe, (ListType, TupleType)), - (adescribe, (N.ndarray,)) ) - -## DISTRIBUTION TESTS - - skewtest = Dispatch ( (askewtest, (ListType, TupleType)), - (askewtest, (N.ndarray,)) ) - kurtosistest = Dispatch ( (akurtosistest, (ListType, TupleType)), - (akurtosistest, (N.ndarray,)) ) - normaltest = Dispatch ( (anormaltest, (ListType, TupleType)), - (anormaltest, (N.ndarray,)) ) - -## FREQUENCY STATS: - itemfreq = Dispatch ( (litemfreq, (ListType, TupleType)), - (aitemfreq, (N.ndarray,)) ) - scoreatpercentile = Dispatch ( (lscoreatpercentile, (ListType, TupleType)), - (ascoreatpercentile, (N.ndarray,)) ) - percentileofscore = Dispatch ( (lpercentileofscore, (ListType, TupleType)), - (apercentileofscore, (N.ndarray,)) ) - histogram = Dispatch ( (lhistogram, (ListType, TupleType)), - (ahistogram, (N.ndarray,)) ) - cumfreq = Dispatch ( (lcumfreq, (ListType, TupleType)), - (acumfreq, (N.ndarray,)) ) - relfreq = Dispatch ( (lrelfreq, (ListType, TupleType)), - (arelfreq, (N.ndarray,)) ) - -## VARIABILITY: - obrientransform = Dispatch ( (lobrientransform, (ListType, TupleType)), - (aobrientransform, (N.ndarray,)) ) - samplevar = Dispatch ( (lsamplevar, (ListType, TupleType)), - (asamplevar, (N.ndarray,)) ) - samplestdev = Dispatch ( (lsamplestdev, (ListType, TupleType)), - (asamplestdev, (N.ndarray,)) ) - signaltonoise = Dispatch( (asignaltonoise, (N.ndarray,)),) - var = Dispatch ( (lvar, (ListType, TupleType)), - (avar, (N.ndarray,)) ) - stdev = Dispatch ( (lstdev, (ListType, TupleType)), - (astdev, (N.ndarray,)) ) - sterr = Dispatch ( (lsterr, (ListType, TupleType)), - (asterr, (N.ndarray,)) ) - sem = Dispatch ( (lsem, (ListType, TupleType)), - (asem, (N.ndarray,)) ) - z = Dispatch ( (lz, (ListType, TupleType)), - (az, (N.ndarray,)) ) - zs = Dispatch ( (lzs, (ListType, TupleType)), - (azs, (N.ndarray,)) ) - -## TRIMMING FCNS: - threshold = Dispatch( (athreshold, (N.ndarray,)),) - trimboth = Dispatch ( (ltrimboth, (ListType, TupleType)), - (atrimboth, (N.ndarray,)) ) - trim1 = Dispatch ( (ltrim1, (ListType, TupleType)), - (atrim1, (N.ndarray,)) ) - -## CORRELATION FCNS: - paired = Dispatch ( (lpaired, (ListType, TupleType)), - (apaired, (N.ndarray,)) ) - lincc = Dispatch ( (llincc, (ListType, TupleType)), - (alincc, (N.ndarray,)) ) - pearsonr = Dispatch ( (lpearsonr, (ListType, TupleType)), - (apearsonr, (N.ndarray,)) ) - spearmanr = Dispatch ( (lspearmanr, (ListType, TupleType)), - (aspearmanr, (N.ndarray,)) ) - pointbiserialr = Dispatch ( (lpointbiserialr, (ListType, TupleType)), - (apointbiserialr, (N.ndarray,)) ) - kendalltau = Dispatch ( (lkendalltau, (ListType, TupleType)), - (akendalltau, (N.ndarray,)) ) - linregress = Dispatch ( (llinregress, (ListType, TupleType)), - (alinregress, (N.ndarray,)) ) - -## INFERENTIAL STATS: - ttest_1samp = Dispatch ( (lttest_1samp, (ListType, TupleType)), - (attest_1samp, (N.ndarray,)) ) - ttest_ind = Dispatch ( (lttest_ind, (ListType, TupleType)), - (attest_ind, (N.ndarray,)) ) - ttest_rel = Dispatch ( (lttest_rel, (ListType, TupleType)), - (attest_rel, (N.ndarray,)) ) - chisquare = Dispatch ( (lchisquare, (ListType, TupleType)), - (achisquare, (N.ndarray,)) ) - ks_2samp = Dispatch ( (lks_2samp, (ListType, TupleType)), - (aks_2samp, (N.ndarray,)) ) - mannwhitneyu = Dispatch ( (lmannwhitneyu, (ListType, TupleType)), - (amannwhitneyu, (N.ndarray,)) ) - tiecorrect = Dispatch ( (ltiecorrect, (ListType, TupleType)), - (atiecorrect, (N.ndarray,)) ) - ranksums = Dispatch ( (lranksums, (ListType, TupleType)), - (aranksums, (N.ndarray,)) ) - wilcoxont = Dispatch ( (lwilcoxont, (ListType, TupleType)), - (awilcoxont, (N.ndarray,)) ) - kruskalwallish = Dispatch ( (lkruskalwallish, (ListType, TupleType)), - (akruskalwallish, (N.ndarray,)) ) - friedmanchisquare = Dispatch ( (lfriedmanchisquare, (ListType, TupleType)), - (afriedmanchisquare, (N.ndarray,)) ) - -## PROBABILITY CALCS: - chisqprob = Dispatch ( (lchisqprob, (IntType, FloatType)), - (achisqprob, (N.ndarray,)) ) - zprob = Dispatch ( (lzprob, (IntType, FloatType)), - (azprob, (N.ndarray,)) ) - ksprob = Dispatch ( (lksprob, (IntType, FloatType)), - (aksprob, (N.ndarray,)) ) - fprob = Dispatch ( (lfprob, (IntType, FloatType)), - (afprob, (N.ndarray,)) ) - betacf = Dispatch ( (lbetacf, (IntType, FloatType)), - (abetacf, (N.ndarray,)) ) - betai = Dispatch ( (lbetai, (IntType, FloatType)), - (abetai, (N.ndarray,)) ) - erfcc = Dispatch ( (lerfcc, (IntType, FloatType)), - (aerfcc, (N.ndarray,)) ) - gammln = Dispatch ( (lgammln, (IntType, FloatType)), - (agammln, (N.ndarray,)) ) - -## ANOVA FUNCTIONS: - F_oneway = Dispatch ( (lF_oneway, (ListType, TupleType)), - (aF_oneway, (N.ndarray,)) ) - F_value = Dispatch ( (lF_value, (ListType, TupleType)), - (aF_value, (N.ndarray,)) ) - -## SUPPORT FUNCTIONS: - incr = Dispatch ( (lincr, (ListType, TupleType, N.ndarray)), ) - sum = Dispatch ( (lsum, (ListType, TupleType)), - (asum, (N.ndarray,)) ) - cumsum = Dispatch ( (lcumsum, (ListType, TupleType)), - (acumsum, (N.ndarray,)) ) - ss = Dispatch ( (lss, (ListType, TupleType)), - (ass, (N.ndarray,)) ) - summult = Dispatch ( (lsummult, (ListType, TupleType)), - (asummult, (N.ndarray,)) ) - square_of_sums = Dispatch ( (lsquare_of_sums, (ListType, TupleType)), - (asquare_of_sums, (N.ndarray,)) ) - sumdiffsquared = Dispatch ( (lsumdiffsquared, (ListType, TupleType)), - (asumdiffsquared, (N.ndarray,)) ) - shellsort = Dispatch ( (lshellsort, (ListType, TupleType)), - (ashellsort, (N.ndarray,)) ) - rankdata = Dispatch ( (lrankdata, (ListType, TupleType)), - (arankdata, (N.ndarray,)) ) - findwithin = Dispatch ( (lfindwithin, (ListType, TupleType)), - (afindwithin, (N.ndarray,)) ) - -###################### END OF NUMERIC FUNCTION BLOCK ##################### - -###################### END OF STATISTICAL FUNCTIONS ###################### - -except ImportError: - pass diff --git a/ete2/coretype/__init__.py b/ete2/coretype/__init__.py deleted file mode 100644 index 0dc0832..0000000 --- a/ete2/coretype/__init__.py +++ /dev/null @@ -1,41 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - diff --git a/ete2/coretype/__init__.pyc b/ete2/coretype/__init__.pyc deleted file mode 100644 index 5e61df3..0000000 Binary files a/ete2/coretype/__init__.pyc and /dev/null differ diff --git a/ete2/coretype/arraytable.py b/ete2/coretype/arraytable.py deleted file mode 100644 index 8151578..0000000 --- a/ete2/coretype/arraytable.py +++ /dev/null @@ -1,265 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - - -import sys -import re -import math -from os import path - -import numpy -from ete2.parser.text_arraytable import write_arraytable, read_arraytable - -__all__ = ["ArrayTable"] - -class ArrayTable(object): - """This object is thought to work with matrix datasets (like - microarrays). It allows to load the matrix an access easily to row - and column vectors. """ - - def __repr__(self): - return "ArrayTable (%s)" %hex(self.__hash__()) - - def __str__(self): - return str(self.matrix) - - def __init__(self, matrix_file=None, mtype="float"): - self.colNames = [] - self.rowNames = [] - self.colValues = {} - self.rowValues = {} - self.matrix = None - self.mtype = None - - # If matrix file is supplied - if matrix_file is not None: - read_arraytable(matrix_file, \ - mtype=mtype, \ - arraytable_object = self) - - def get_row_vector(self,rowname): - """ Returns the vector associated to the given row name """ - return self.rowValues.get(rowname,None) - - - def get_column_vector(self,colname): - """ Returns the vector associated to the given column name """ - return self.colValues.get(colname,None) - - - def get_several_column_vectors(self,colnames): - """ Returns a list of vectors associated to several column names """ - vectors = [self.colValues[cname] for cname in colnames] - return numpy.array(vectors) - - def get_several_row_vectors(self,rownames): - """ Returns a list vectors associated to several row names """ - vectors = [self.rowValues[rname] for rname in rownames] - return numpy.array(vectors) - - def remove_column(self,colname): - """Removes the given column form the current dataset """ - col_value = self.colValues.pop(colname, None) - if col_value != None: - new_indexes = range(len(self.colNames)) - index = self.colNames.index(colname) - self.colNames.pop(index) - new_indexes.pop(index) - newmatrix = self.matrix.swapaxes(0,1) - newmatrix = newmatrix[new_indexes].swapaxes(0,1) - self._link_names2matrix(newmatrix) - - def merge_columns(self, groups, grouping_criterion): - """ Returns a new ArrayTable object in which columns are - merged according to a given criterion. - - 'groups' argument must be a dictionary in which keys are the - new column names, and each value is the list of current - column names to be merged. - - 'grouping_criterion' must be 'min', 'max' or 'mean', and - defines how numeric values will be merged. - - Example: - my_groups = {'NewColumn':['column5', 'column6']} - new_Array = Array.merge_columns(my_groups, 'max') - - """ - - if grouping_criterion == "max": - grouping_f = get_max_vector - elif grouping_criterion == "min": - grouping_f = get_min_vector - elif grouping_criterion == "mean": - grouping_f = get_mean_vector - else: - raise ValueError, "grouping_criterion not supported. Use max|min|mean " - - grouped_array = self.__class__() - grouped_matrix = [] - colNames = [] - alltnames = set([]) - for gname,tnames in groups.iteritems(): - all_vectors=[] - for tn in tnames: - if tn not in self.colValues: - raise ValueError, str(tn)+" column not found." - if tn in alltnames: - raise ValueError, str(tn)+" duplicated column name for merging" - alltnames.add(tn) - vector = self.get_column_vector(tn).astype(float) - all_vectors.append(vector) - # Store the group vector = max expression of all items in group - grouped_matrix.append(grouping_f(all_vectors)) - # store group name - colNames.append(gname) - - for cname in self.colNames: - if cname not in alltnames: - grouped_matrix.append(self.get_column_vector(cname)) - colNames.append(cname) - - grouped_array.rowNames= self.rowNames - grouped_array.colNames= colNames - vmatrix = numpy.array(grouped_matrix).transpose() - grouped_array._link_names2matrix(vmatrix) - return grouped_array - - def transpose(self): - """ Returns a new ArrayTable in which current matrix is transposed. """ - - transposedA = self.__class__() - transposedM = self.matrix.transpose() - transposedA.colNames = list(self.rowNames) - transposedA.rowNames = list(self.colNames) - transposedA._link_names2matrix(transposedM) - - # Check that everything is ok - # for n in self.colNames: - # print self.get_column_vector(n) == transposedA.get_row_vector(n) - # for n in self.rowNames: - # print self.get_row_vector(n) == transposedA.get_column_vector(n) - return transposedA - - def _link_names2matrix(self, m): - """ Synchronize curent column and row names to the given matrix""" - if len(self.rowNames) != m.shape[0]: - raise ValueError , "Expecting matrix with %d rows" % m.size[0] - - if len(self.colNames) != m.shape[1]: - raise ValueError , "Expecting matrix with %d columns" % m.size[1] - - self.matrix = m - self.colValues.clear() - self.rowValues.clear() - # link columns names to vectors - i = 0 - for colname in self.colNames: - self.colValues[colname] = self.matrix[:,i] - i+=1 - # link row names to vectors - i = 0 - for rowname in self.rowNames: - self.rowValues[rowname] = self.matrix[i,:] - i+=1 - - def write(self, fname, colnames=None): - write_arraytable(self, fname, colnames=colnames) - - - -def get_centroid_dist(vcenter,vlist,fdist): - d = 0.0 - for v in vlist: - d += fdist(v,vcenter) - return 2*(d / len(vlist)) - -def get_average_centroid_linkage_dist(vcenter1,vlist1,vcenter2,vlist2,fdist): - d1,d2 = 0.0, 0.0 - for v in vlist1: - d1 += fdist(v,vcenter2) - for v in vlist2: - d2 += fdist(v,vcenter1) - return (d1+d2) / (len(vlist1)+len(vlist2)) - -def safe_mean(values): - """ Returns mean value discarding non finite values """ - valid_values = [] - for v in values: - if numpy.isfinite(v): - valid_values.append(v) - return numpy.mean(valid_values), numpy.std(valid_values) - -def safe_mean_vector(vectors): - """ Returns mean profile discarding non finite values """ - # if only one vector, avg = itself - if len(vectors)==1: - return vectors[0], numpy.zeros(len(vectors[0])) - # Takes the vector length form the first item - length = len(vectors[0]) - - safe_mean = [] - safe_std = [] - - for pos in xrange(length): - pos_mean = [] - for v in vectors: - if numpy.isfinite(v[pos]): - pos_mean.append(v[pos]) - safe_mean.append(numpy.mean(pos_mean)) - safe_std.append(numpy.std(pos_mean)) - return safe_mean, safe_std - -def get_mean_vector(vlist): - a = numpy.array(vlist) - return numpy.mean(a,0) - -def get_median_vector(vlist): - a = numpy.array(vlist) - return numpy.median(a) - -def get_max_vector(vlist): - a = numpy.array(vlist) - return numpy.max(a,0) - -def get_min_vector(vlist): - a = numpy.array(vlist) - return numpy.min(a,0) diff --git a/ete2/coretype/arraytable.pyc b/ete2/coretype/arraytable.pyc deleted file mode 100644 index f71bab2..0000000 Binary files a/ete2/coretype/arraytable.pyc and /dev/null differ diff --git a/ete2/coretype/seqgroup.py b/ete2/coretype/seqgroup.py deleted file mode 100644 index 87422bb..0000000 --- a/ete2/coretype/seqgroup.py +++ /dev/null @@ -1,165 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -""" -The 'seqgroup' module provides methods and classes to operate with -Multiple Sequence Files, including Multiple Sequence Alignments. - -Currently, Fasta, Phylip sequencial and Phylip interleaved formats are -supported. -""" - -from ete2.parser.fasta import read_fasta, write_fasta -from ete2.parser.paml import read_paml, write_paml -from ete2.parser.phylip import read_phylip, write_phylip - -__all__ = ["SeqGroup"] - -class SeqGroup(object): - """ - SeqGroup class can be used to store a set of sequences (aligned - or not). - - - :argument sequences: Path to the file containing the sequences or, - alternatively, the text string containing the same - information. - - :argument fasta format: the format in which sequences are - encoded. Current supported formats are: ``fasta``, ``phylip`` - (phylip sequencial) and ``iphylip`` (phylip - interleaved). Phylip format forces sequence names to a maximum - of 10 chars. To avoid this effect, you can use the relaxed - phylip format: ``phylip_relaxed`` and ``iphylip_relaxed``. - - :: - - msf = ">seq1\\nAAAAAAAAAAA\\n>seq2\\nTTTTTTTTTTTTT\\n" - seqs = SeqGroup(msf, format="fasta") - print seqs.get_seq("seq1") - """ - - def __len__(self): - return len(self.id2seq) - - def __contains__(self, item): - return item in self.name2id - - def __str__(self): - return write_fasta(self) - - def __iter__(self): - return self.iter_entries() - - def __init__(self, sequences=None , format="fasta", fix_duplicates=True, **kwargs): - self.parsers = { - "fasta": [read_fasta, write_fasta, {}], - "phylip": [read_phylip, write_phylip, {"interleaved":False, "relaxed":False}], - "iphylip": [read_phylip, write_phylip, {"interleaved":True, "relaxed":False}], - "phylip_relaxed": [read_phylip, write_phylip, {"interleaved":False, "relaxed":True}], - "iphylip_relaxed": [read_phylip, write_phylip, {"interleaved":True, "relaxed":True}], - "paml" : [read_paml , write_paml , kwargs ] - } - - self.id2name = {} - self.name2id = {} - self.id2comment= {} - self.id2seq = {} - - if sequences is not None: - format = format.lower() - if format in self.parsers: - read = self.parsers[format][0] - args = self.parsers[format][2] - read(sequences, obj=self, fix_duplicates=fix_duplicates, **args) - else: - raise ValueError, "Unsupported format: [%s]" %format - - def __repr__(self): - return "SeqGroup (%s)" %hex(self.__hash__()) - - def write(self, format="fasta", outfile=None): - """ Returns the text representation of the sequences in the - supplied given format (default=FASTA). If "oufile" argument is - used, the result is written into the given path.""" - - format = format.lower() - if format in self.parsers: - write = self.parsers[format][1] - args = self.parsers[format][2] - return write(self, outfile, **args) - else: - raise ValueError, "Unsupported format: [%s]" %format - - def iter_entries(self): - """ Returns an iterator over all sequences in the - collection. Each item is a tuple with the sequence name, - sequence, and sequence comments """ - for i, seq in self.id2seq.iteritems(): - yield self.id2name[i], seq, self.id2comment.get(i, []) - - def get_seq(self, name): - """ Returns the sequence associated to a given entry name.""" - return self.id2seq[self.name2id[name]] - - def get_entries(self): - """ Returns the list of entries currently stored.""" - keys = self.id2seq.keys() - seqs = self.id2seq.values() - comments = [self.id2comment.get(x, []) for x in keys] - names = map(lambda x: self.id2name[x], keys) - return zip(names, seqs, comments) - - def set_seq(self, name, seq, comments = None): - """Updates or adds a sequence """ - if comments is None: - comments = [] - name = name.strip() - seq = seq.replace(" ", "") - seq = seq.replace("\t", "") - seq = seq.replace("\n", "") - seq = seq.replace("\r", "") - seqid = self.name2id.get(name, max([0]+self.name2id.values())+1) - self.name2id[name] = seqid - self.id2name[seqid] = name - self.id2comment[seqid] = comments - self.id2seq[seqid] = seq - diff --git a/ete2/coretype/seqgroup.pyc b/ete2/coretype/seqgroup.pyc deleted file mode 100644 index 7cd10da..0000000 Binary files a/ete2/coretype/seqgroup.pyc and /dev/null differ diff --git a/ete2/coretype/tree.py b/ete2/coretype/tree.py deleted file mode 100644 index a13e638..0000000 --- a/ete2/coretype/tree.py +++ /dev/null @@ -1,1957 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#START_LICENSE########################################################### -# -# Copyright (C) 2009 by Jaime Huerta Cepas. All rights reserved. -# email: jhcepas@gmail.com -# -# This file is part of the Environment for Tree Exploration program (ETE). -# http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# #END_LICENSE############################################################# -import os -import cPickle -import random -import copy -from collections import deque -import itertools -from ete2.parser.newick import read_newick, write_newick - -# the following imports are necessary to set fixed styles and faces -try: - from ete2.treeview.main import NodeStyle, _FaceAreas, FaceContainer, FACE_POSITIONS - from ete2.treeview.faces import Face -except ImportError: - TREEVIEW = False -else: - TREEVIEW = True - -__all__ = ["Tree", "TreeNode"] - -DEFAULT_COMPACT = False -DEFAULT_SHOWINTERNAL = False -DEFAULT_DIST = 1.0 -DEFAULT_SUPPORT = 1.0 -DEFAULT_NAME = "NoName" - -class TreeError(Exception): - """ - A problem occurred during a TreeNode operation - """ - def __init__(self, value=''): - self.value = value - def __str__(self): - return repr(self.value) - -class TreeNode(object): - """ - TreeNode (Tree) class is used to store a tree structure. A tree - consists of a collection of TreeNode instances connected in a - hierarchical way. Trees can be loaded from the New Hampshire Newick - format (newick). - - :argument newick: Path to the file containing the tree or, alternatively, - the text string containing the same information. - - :argument 0 format: subnewick format - - .. table:: - - ====== ============================================== - FORMAT DESCRIPTION - ====== ============================================== - 0 flexible with support values - 1 flexible with internal node names - 2 all branches + leaf names + internal supports - 3 all branches + all names - 4 leaf branches + leaf names - 5 internal and leaf branches + leaf names - 6 internal branches + leaf names - 7 leaf branches + all names - 8 all names - 9 leaf names - 100 topology only - ====== ============================================== - - :returns: a tree node object which represents the base of the tree. - - ** Examples: ** - - :: - - t1 = Tree() # creates an empty tree - t2 = Tree('(A:1,(B:1,(C:1,D:1):0.5):0.5);') - t3 = Tree('/home/user/myNewickFile.txt') - """ - - def _get_dist(self): - return self._dist - def _set_dist(self, value): - try: - self._dist = float(value) - except ValueError: - raise - - def _get_support(self): - return self._support - def _set_support(self, value): - try: - self._support = float(value) - except ValueError: - raise - - def _get_up(self): - return self._up - def _set_up(self, value): - if type(value) == type(self) or value is None: - self._up = value - else: - raise ValueError("bad node_up type") - - def _get_children(self): - return self._children - def _set_children(self, value): - if type(value) == list and \ - len(set([type(n)==type(self) for n in value]))<2: - self._children = value - else: - raise ValueError("bad children type") - - def _get_style(self): - if self._img_style is None: - self._set_style(None) - - return self._img_style - - def _set_style(self, value): - self.set_style(value) - - #: Branch length distance to parent node. Default = 0.0 - img_style = property(fget=_get_style, fset=_set_style) - - #: Branch length distance to parent node. Default = 0.0 - dist = property(fget=_get_dist, fset=_set_dist) - #: Branch support for current node - support = property(fget=_get_support, fset=_set_support) - #: Pointer to parent node - up = property(fget=_get_up, fset=_set_up) - #: A list of children nodes - children = property(fget=_get_children, fset=_set_children) - - def _set_face_areas(self, value): - if isinstance(value, _FaceAreas): - self._faces = value - else: - raise ValueError("[%s] is not a valid FaceAreas instance" %type(value)) - - def _get_face_areas(self): - if not hasattr(self, "_faces"): - self._faces = _FaceAreas() - return self._faces - - faces = property(fget=_get_face_areas, \ - fset=_set_face_areas) - - def __init__(self, newick=None, format=0, dist=None, support=None, - name=None): - self._children = [] - self._up = None - self._dist = DEFAULT_DIST - self._support = DEFAULT_SUPPORT - self._img_style = None - self.features = set([]) - # Add basic features - self.features.update(["dist", "support", "name"]) - if dist is not None: - self.dist = dist - if support is not None: - self.support = support - - self.name = name if name is not None else DEFAULT_NAME - - # Initialize tree - if newick is not None: - read_newick(newick, root_node = self, format=format) - - - def __nonzero__(self): - return True - - def __repr__(self): - return "Tree node '%s' (%s)" %(self.name, hex(self.__hash__())) - - def __and__(self, value): - """ This allows to execute tree&'A' to obtain the descendant node - whose name is A""" - value=str(value) - try: - first_match = self.iter_search_nodes(name=value).next() - 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): - """Node len returns number of children.""" - return len(self.get_leaves()) - - def __iter__(self): - """ Iterator over leaf nodes""" - return self.iter_leaves() - - def add_feature(self, pr_name, pr_value): - """ - Add or update a node's feature. - """ - setattr(self, pr_name, pr_value) - self.features.add(pr_name) - - def add_features(self, **features): - """ - Add or update several features. """ - for fname, fvalue in features.iteritems(): - setattr(self, fname, fvalue) - self.features.add(fname) - - def del_feature(self, pr_name): - """ - Permanently deletes a node's feature. - """ - if hasattr(self, pr_name): - delattr(self, pr_name) - self.features.remove(pr_name) - - # Topology management - def add_child(self, child=None, name=None, dist=None, support=None): - """ - Adds a new child to this node. If child node is not suplied - as an argument, a new node instance will be created. - - :argument None child: the node instance to be added as a child. - :argument None name: the name that will be given to the child. - :argument None dist: the distance from the node to the child. - :argument None support': the support value of child partition. - - :returns: The child node instance - - """ - if child is None: - child = self.__class__() - - if name is not None: - child.name = name - if dist is not None: - child.dist = dist - if support is not None: - child.support = support - - self.children.append(child) - child.up = self - return child - - def remove_child(self, child): - """ - Removes a child from this node (parent and child - nodes still exit but are no longer connected). - """ - try: - self.children.remove(child) - except ValueError, e: - raise TreeError, e - else: - child.up = None - return child - - def add_sister(self, sister=None, name=None, dist=None): - """ - Adds a sister to this node. If sister node is not supplied - as an argument, a new TreeNode instance will be created and - returned. - """ - if self.up == None: - raise TreeError("A parent node is required to add a sister") - else: - return self.up.add_child(child=sister, name=name, dist=dist) - - def remove_sister(self, sister=None): - """ - Removes a node's sister node. It has the same effect as - **`TreeNode.up.remove_child(sister)`** - - If a sister node is not supplied, the first sister will be deleted - and returned. - - :argument sister: A node instance - - :return: The node removed - """ - sisters = self.get_sisters() - if len(sisters)>0: - if sister==None: - sister = sisters.pop(0) - return self.up.remove_child(sister) - - def delete(self, prevent_nondicotomic=True, preserve_branch_length=False): - """ - Deletes node from the tree structure. Notice that this method - makes 'disappear' the node from the tree structure. This means - that children from the deleted node are transferred to the - next available parent. - - :param True prevent_nondicotomic: When True (default), delete - function will be execute recursively to prevent single-child - nodes. - - :param False preserve_branch_length: If True, branch lengths - of the deleted nodes are transferred (summed up) to its - parent's branch, thus keeping original distances among nodes. - - **Example:** - - :: - - / C - root-| - | / B - \--- H | - \ A - - > root.delete(H) will produce this structure: - - / C - | - root-|--B - | - \ A - - """ - parent = self.up - if parent: - for ch in self.children: - if preserve_branch_length: - ch.dist += self.dist - parent.add_child(ch) - - parent.remove_child(self) - - # Avoids parents with only one child - if prevent_nondicotomic and parent and\ - len(parent.children)<2: - parent.delete(prevent_nondicotomic=False, - preserve_branch_length=preserve_branch_length) - - - def detach(self): - """ - Detachs this node (and all its descendants) from its parent - and returns the referent to itself. - - Detached node conserves all its structure of descendants, and can - be attached to another node through the 'add_child' function. This - mechanism can be seen as a cut and paste. - """ - - if self.up: - self.up.children.remove(self) - self.up = None - return self - - - def prune(self, nodes, preserve_branch_length=False): - """Prunes the topology of a node in order to conserve only a - selected list of leaf or internal nodes. The minimum number of - internal nodes (the deepest as possible) are kept to conserve - the topological relationship among the provided list of nodes. - - :var nodes: a list of node names or node objects that must be kept - - :param False preserve_branch_length: If True, branch lengths - of the deleted nodes are transferred (summed up) to its - parent's branch, thus keeping original distances among nodes. - - **Examples:** - - :: - - t = Tree("(((A:0.1, B:0.01):0.001, C:0.0001):1.0[&&NHX:name=I], (D:0.00001):0.000001[&&NHX:name=J]):2.0[&&NHX:name=root];") - node_C = t.search_nodes(name="C")[0] - t.prune(["A","D", node_C]) - print t - - """ - def cmp_nodes(x, y): - # if several nodes are in the same path of two kept nodes, - # only one should be maintained. This prioritize internal - # nodes that are already in the to_keep list and then - # deeper nodes (closer to the leaves). - if x in to_keep: - if y not in to_keep: - return -1 - elif y in to_keep: - return 0 - elif n2depth[x] > n2depth[y]: - return -1 - elif n2depth[x] < n2depth[y]: - return 1 - else: - return 0 - - to_keep = set(_translate_nodes(self, *nodes)) - start, node2path = self.get_common_ancestor(to_keep, get_path=True) - - # Calculate which kept nodes are visiting the same nodes in - # their path to the common ancestor. - n2count = {} - n2depth = {} - for seed, path in node2path.iteritems(): - for visited_node in path: - if visited_node not in n2depth: - depth = visited_node.get_distance(start, topology_only=True) - n2depth[visited_node] = depth - if visited_node is not seed: - n2count.setdefault(visited_node, set()).add(seed) - - # if several internal nodes are in the path of exactly the - # same kept nodes, only one should be maintain. - visitors2nodes = {} - for node, visitors in n2count.iteritems(): - # keep nodes connection at least two other nodes - if len(visitors)>1: - visitor_key = frozenset(visitors) - visitors2nodes.setdefault(visitor_key, set()).add(node) - for visitors, nodes in visitors2nodes.iteritems(): - s = sorted(nodes, cmp_nodes) - to_keep.add(s[0]) - - # Detach unvisited branches - if start is not self: - start.detach() - for n in self.get_children(): - n.detach() - for n in start.get_children(): - self.add_child(child=n) - - for n in [self]+self.get_descendants(): - if n not in to_keep: - n.delete(prevent_nondicotomic=False, - preserve_branch_length=preserve_branch_length) - - def swap_children(self): - """ - Swaps current children order. - """ - if len(self.children)>1: - self.children.reverse() - - # def prune_OLD(self, nodes): - # """ - # Prunes the topology of this node in order to conserve only a - # selected list of leaf or internal nodes. The algorithm deletes - # nodes until getting a consistent topology with a subset of - # nodes. Topology relationships among kept nodes is maintained. - # - # :var nodes: a list of node names or node objects that must be kept - # - # **Examples:** - # - # :: - # - # t = Tree("(((A:0.1, B:0.01):0.001, C:0.0001):1.0[&&NHX:name=I], (D:0.00001):0.000001[&&NHX:name=J]):2.0[&&NHX:name=root];") - # node_C = t.search_nodes(name="C")[0] - # t.prune(["A","D", node_C]) - # print t - # """ - # - # to_keep = set(_translate_nodes(self, *nodes)) - # to_detach = [] - # for node in self.traverse("postorder"): - # for c in node.children: - # if c in to_keep: - # to_keep.add(node) - # break - # if node not in to_keep: - # to_detach.append(node) - # for c in node.children: - # to_detach.remove(c) - # for node in to_detach: - # node.detach() - # for node in to_keep: - # if len(node.children) == 1: - # node.delete() - # if len(self.children)==1 and self.children[0] not in to_keep: - # self.children[0].delete() - - # ##################### - # Tree traversing - # ##################### - - - def get_children(self): - """ - Returns an independent list of node's children. - """ - return [ch for ch in self.children] - - def get_sisters(self): - """ - Returns an indepent list of sister nodes. - """ - if self.up!=None: - return [ch for ch in self.up.children if ch!=self] - else: - return [] - - def iter_leaves(self, is_leaf_fn=None): - """ - Returns an iterator over the leaves under this node. - - :argument None is_leaf_fn: See :func:`TreeNode.traverse` for - documentation. - """ - for n in self.traverse(strategy="preorder", is_leaf_fn=is_leaf_fn): - if not is_leaf_fn: - if n.is_leaf(): - yield n - else: - if is_leaf_fn(n): - yield n - - def get_leaves(self, is_leaf_fn=None): - """ - Returns the list of terminal nodes (leaves) under this node. - - :argument None is_leaf_fn: See :func:`TreeNode.traverse` for - documentation. - """ - return [n for n in self.iter_leaves(is_leaf_fn=is_leaf_fn)] - - def iter_leaf_names(self, is_leaf_fn=None): - """ - Returns an iterator over the leaf names under this node. - - :argument None is_leaf_fn: See :func:`TreeNode.traverse` for - documentation. - """ - for n in self.iter_leaves(is_leaf_fn=is_leaf_fn): - yield n.name - - def get_leaf_names(self, is_leaf_fn=None): - """ - Returns the list of terminal node names under the current - node. - - :argument None is_leaf_fn: See :func:`TreeNode.traverse` for - documentation. - """ - return [name for name in self.iter_leaf_names(is_leaf_fn=is_leaf_fn)] - - def iter_descendants(self, strategy="levelorder", is_leaf_fn=None): - """ - Returns an iterator over all descendant nodes. - - :argument None is_leaf_fn: See :func:`TreeNode.traverse` for - documentation. - """ - for n in self.traverse(strategy=strategy, is_leaf_fn=is_leaf_fn): - if n is not self: - yield n - - def get_descendants(self, strategy="levelorder", is_leaf_fn=None): - """ - Returns a list of all (leaves and internal) descendant nodes. - - :argument None is_leaf_fn: See :func:`TreeNode.traverse` for - documentation. - """ - return [n for n in self.iter_descendants(strategy=strategy, \ - is_leaf_fn=is_leaf_fn)] - - def traverse(self, strategy="levelorder", is_leaf_fn=None): - """ - Returns an iterator to traverse the tree structure under this - node. - - :argument "levelorder" strategy: set the way in which tree - will be traversed. Possible values are: "preorder" (first - parent and then children) 'postorder' (first children and - the parent) and "levelorder" (nodes are visited in order - from root to leaves) - - :argument None is_leaf_fn: If supplied, ``is_leaf_fn`` - function will be used to interrogate nodes about if they - are terminal or internal. ``is_leaf_fn`` function should - receive a node instance as first argument and return True - or False. Use this argument to traverse a tree by - dynamically collapsing internal nodes matching - ``is_leaf_fn``. - """ - if strategy=="preorder": - return self._iter_descendants_preorder(is_leaf_fn=is_leaf_fn) - elif strategy=="levelorder": - return self._iter_descendants_levelorder(is_leaf_fn=is_leaf_fn) - elif strategy=="postorder": - return self._iter_descendants_postorder(is_leaf_fn=is_leaf_fn) - - def _iter_descendants_postorder_recursive(self, is_leaf_fn=None): - """ - Iterate over all desdecendant nodes. - """ - if not is_leaf_fn or not is_leaf_fn(self): - for ch in self.children: - for node in ch._iter_descendants_postorder(is_leaf_fn=is_leaf_fn): - yield node - yield self - - def iter_prepostorder(self, is_leaf_fn=None): - """ - Iterate over all nodes in a tree yielding every node in both - pre and post order. Each iteration returns a postorder flag - (True if node is being visited in postorder) and a node - instance. - """ - to_visit = [self] - if is_leaf_fn is not None: - _leaf = is_leaf_fn - else: - _leaf = self.__class__.is_leaf - - while to_visit: - node = to_visit.pop(-1) - try: - node = node[1] - except TypeError: - # PREORDER ACTIONS - yield (False, node) - if not _leaf(node): - # ADD CHILDREN - to_visit.extend(reversed(node.children + [[1, node]])) - else: - #POSTORDER ACTIONS - yield (True, node) - - def _iter_descendants_postorder(self, is_leaf_fn=None): - to_visit = [self] - if is_leaf_fn is not None: - _leaf = is_leaf_fn - else: - _leaf = self.__class__.is_leaf - - while to_visit: - node = to_visit.pop(-1) - try: - node = node[1] - except TypeError: - # PREORDER ACTIONS - if not _leaf(node): - # ADD CHILDREN - to_visit.extend(reversed(node.children + [[1, node]])) - else: - yield node - else: - #POSTORDER ACTIONS - yield node - - def _iter_descendants_levelorder(self, is_leaf_fn=None): - """ - Iterate over all desdecendant nodes. - """ - tovisit = deque([self]) - while len(tovisit)>0: - node = tovisit.popleft() - yield node - if not is_leaf_fn or not is_leaf_fn(node): - tovisit.extend(node.children) - - def _iter_descendants_preorder(self, is_leaf_fn=None): - """ - Iterator over all descendant nodes. - """ - to_visit = deque() - node = self - while node is not None: - yield node - if not is_leaf_fn or not is_leaf_fn(node): - to_visit.extendleft(reversed(node.children)) - try: - node = to_visit.popleft() - except: - node = None - - def iter_ancestors(self): - '''versionadded: 2.2 - - Iterates over the list of all ancestor nodes from current node - to the current tree root. - - ''' - node = self - while node.up is not None: - yield node.up - node = node.up - - def get_ancestors(self): - '''versionadded: 2.2 - - Returns the list of all ancestor nodes from current node to - the current tree root. - - ''' - return [n for n in self.iter_ancestors()] - - def describe(self): - """ - Prints general information about this node and its - connections. - """ - if len(self.get_tree_root().children)==2: - rooting = "Yes" - elif len(self.get_tree_root().children)>2: - rooting = "No" - else: - rooting = "Unknown" - max_node, max_dist = self.get_farthest_leaf() - cached_content = self.get_cached_content() - print "Number of leaf nodes:\t%d" % len(cached_content[self]) - print "Number of internal nodes:\t%d" % len(cached_content) - print "Rooted:\t%s" %rooting - print "Most distant node:\t%s" %max_node.name - print "Max. distance:\t%f" %max_dist - - def write(self, features=None, outfile=None, format=0, is_leaf_fn=None, - format_root_node=False): - """ - Returns the newick representation of current node. Several - arguments control the way in which extra data is shown for - every node: - - :argument features: a list of feature names to be exported - using the Extended Newick Format (i.e. features=["name", - "dist"]). Use an empty list to export all available features - in each node (features=[]) - - :argument outfile: writes the output to a given file - - :argument format: defines the newick standard used to encode the - tree. See tutorial for details. - - :argument False format_root_node: If True, it allows features - and branch information from root node to be exported as a - part of the newick text string. For newick compatibility - reasons, this is False by default. - - :argument is_leaf_fn: See :func:`TreeNode.traverse` for - documentation. - - **Example:** - - :: - - t.get_newick(features=["species","name"], format=1) - - """ - - nw = write_newick(self, features = features, format=format, - is_leaf_fn=is_leaf_fn, - format_root_node=format_root_node) - if outfile is not None: - open(outfile, "w").write(nw) - else: - return nw - - def get_tree_root(self): - """ - Returns the absolute root node of current tree structure. - """ - root = self - while root.up is not None: - root = root.up - return root - - def get_common_ancestor(self, *target_nodes, **kargs): - """ - Returns the first common ancestor between this node and a given - list of 'target_nodes'. - - **Examples:** - - :: - - t = tree.Tree("(((A:0.1, B:0.01):0.001, C:0.0001):1.0[&&NHX:name=common], (D:0.00001):0.000001):2.0[&&NHX:name=root];") - A = t.get_descendants_by_name("A")[0] - C = t.get_descendants_by_name("C")[0] - common = A.get_common_ancestor(C) - print common.name - - """ - - get_path = kargs.get("get_path", False) - - if len(target_nodes) == 1 and type(target_nodes[0]) \ - in set([set, tuple, list, frozenset]): - target_nodes = target_nodes[0] - - # Convert node names into node instances - target_nodes = _translate_nodes(self, *target_nodes) - - # If only one node is provided, use self as the second target - if type(target_nodes) != list: - target_nodes = [target_nodes, self] - elif len(target_nodes)==1: - target_nodes = tree_nodes.append(self) - - n2path = {} - reference = [] - ref_node = None - for n in target_nodes: - current = n - while current: - n2path.setdefault(n, set()).add(current) - if not ref_node: - reference.append(current) - current = current.up - if not ref_node: - ref_node = n - - common = None - for n in reference: - broken = False - for node, path in n2path.iteritems(): - if node is not ref_node and n not in path: - broken = True - break - - if not broken: - common = n - break - if not common: - raise ValueError("Nodes are not connected!") - - if get_path: - return common, n2path - else: - return common - - def iter_search_nodes(self, **conditions): - """ - Search nodes in an interative way. Matches are being yield as - they are being found. This avoids to scan the full tree - topology before returning the first matches. Useful when - dealing with huge trees. - """ - - for n in self.traverse(): - conditions_passed = 0 - for key, value in conditions.iteritems(): - if hasattr(n, key) and getattr(n, key) == value: - conditions_passed +=1 - if conditions_passed == len(conditions): - yield n - - def search_nodes(self, **conditions): - """ - Returns the list of nodes matching a given set of conditions. - - **Example:** - - :: - - tree.search_nodes(dist=0.0, name="human") - - """ - matching_nodes = [] - for n in self.iter_search_nodes(**conditions): - matching_nodes.append(n) - return matching_nodes - - def get_leaves_by_name(self,name): - """ - Returns a list of leaf nodes matching a given name. - """ - return self.search_nodes(name=name, children=[]) - - def is_leaf(self): - """ - Return True if current node is a leaf. - """ - return len(self.children) == 0 - - def is_root(self): - """ - Returns True if current node has no parent - """ - if self.up is None: - return True - else: - return False - - # ########################### - # Distance related functions - # ########################### - def get_distance(self, target, target2=None, topology_only=False): - """ - Returns the distance between two nodes. If only one target is - specified, it returns the distance bewtween the target and the - current node. - - :argument target: a node within the same tree structure. - - :argument target2: a node within the same tree structure. If - not specified, current node is used as target2. - - :argument False topology_only: If set to True, distance will - refer to the number of nodes between target and target2. - - :returns: branch length distance between target and - target2. If topology_only flag is True, returns the number - of nodes between target and target2. - - """ - - if target2 is None: - target2 = self - root = self.get_tree_root() - else: - # is target node under current node? - root = self - - target, target2 = _translate_nodes(root, target, target2) - ancestor = root.get_common_ancestor(target, target2) - if ancestor is None: - raise TreeError, "Nodes are not connected" - - dist = 0.0 - for n in [target2, target]: - current = n - while current != ancestor: - if topology_only: - if current!=target: - dist += 1 - else: - dist += current.dist - current = current.up - return dist - - def get_farthest_node(self, topology_only=False): - """ - Returns the node's farthest descendant or ancestor node, and the - distance to it. - - :argument False topology_only: If set to True, distance - between nodes will be referred to the number of nodes - between them. In other words, topological distance will be - used instead of branch length distances. - - :return: A tuple containing the farthest node referred to the - current node and the distance to it. - - """ - # Init fasthest node to current farthest leaf - farthest_node,farthest_dist = self.get_farthest_leaf(topology_only=topology_only) - prev = self - if topology_only: - cdist = 0 - else: - cdist = prev.dist - current = prev.up - while current is not None: - for ch in current.children: - if ch != prev: - if not ch.is_leaf(): - fnode, fdist = ch.get_farthest_leaf(topology_only=topology_only) - else: - fnode = ch - fdist = 0 - if topology_only: - fdist += 1.0 - else: - fdist += ch.dist - if cdist+fdist > farthest_dist: - farthest_dist = cdist + fdist - farthest_node = fnode - prev = current - if topology_only: - cdist += 1 - else: - cdist += prev.dist - current = prev.up - return farthest_node, farthest_dist - - def get_farthest_leaf(self, topology_only=False): - """ - Returns node's farthest descendant node (which is always a leaf), and the - distance to it. - - :argument False topology_only: If set to True, distance - between nodes will be referred to the number of nodes - between them. In other words, topological distance will be - used instead of branch length distances. - - :return: A tuple containing the farthest leaf referred to the - current node and the distance to it. - """ - max_dist = 0.0 - max_node = None - if self.is_leaf(): - return self, 0.0 - else: - for ch in self.children: - node, d = ch.get_farthest_leaf(topology_only=topology_only) - if topology_only: - d += 1.0 - else: - d += ch.dist - if d>=max_dist: - max_dist = d - max_node = node - return max_node, max_dist - - def get_closest_leaf(self, topology_only=False): - """Returns node's closest descendant leaf and the distance to - it. - - :argument False topology_only: If set to True, distance - between nodes will be referred to the number of nodes - between them. In other words, topological distance will be - used instead of branch length distances. - - :return: A tuple containing the closest leaf referred to the - current node and the distance to it. - - """ - min_dist = None - min_node = None - if self.is_leaf(): - return self, 0.0 - else: - for ch in self.children: - node, d = ch.get_closest_leaf(topology_only=topology_only) - if topology_only: - d += 1.0 - else: - d += ch.dist - if min_dist is None or d (middist): # Deja de subir cuando se pasa del maximo - break - else: - current = current.up - return current - - def populate(self, size, names_library=None, reuse_names=False, - random_branches=False, branch_range=(0,1), - support_range=(0,1)): - """ - Generates a random topology by populating current node. - - :argument None names_library: If provided, names library - (list, set, dict, etc.) will be used to name nodes. - - :argument False reuse_names: If True, node names will not be - necessarily unique, which makes the process a bit more - efficient. - - :argument False random_branches: If True, branch distances and support - values will be randomized. - - :argument (0,1) branch_range: If random_branches is True, this - range of values will be used to generate random distances. - - :argument (0,1) support_range: If random_branches is True, - this range of values will be used to generate random branch - support values. - - """ - NewNode = self.__class__ - - if len(self.children) > 1: - connector = NewNode() - for ch in self.get_children(): - ch.detach() - connector.add_child(child = ch) - root = NewNode() - self.add_child(child = connector) - self.add_child(child = root) - else: - root = self - - next = deque([root]) - for i in xrange(size-1): - if random.randint(0, 1): - p = next.pop() - else: - p = next.popleft() - - c1 = p.add_child() - c2 = p.add_child() - next.extend([c1, c2]) - if random_branches: - c1.dist = random.uniform(*branch_range) - c2.dist = random.uniform(*branch_range) - c1.support = random.uniform(*branch_range) - c2.support = random.uniform(*branch_range) - else: - c1.dist = 1.0 - c2.dist = 1.0 - c1.support = 1.0 - c2.support = 1.0 - - # next contains leaf nodes - charset = "abcdefghijklmnopqrstuvwxyz" - if names_library: - names_library = deque(names_library) - else: - avail_names = itertools.combinations_with_replacement(charset, 10) - for n in next: - if names_library: - if reuse_names: - tname = random.sample(names_library, 1)[0] - else: - tname = names_library.pop() - else: - tname = ''.join(avail_names.next()) - n.name = tname - - - def set_outgroup(self, outgroup): - """ - Sets a descendant node as the outgroup of a tree. This function - can be used to root a tree or even an internal node. - - :argument outgroup: a node instance within the same tree - structure that will be used as a basal node. - - """ - - outgroup = _translate_nodes(self, outgroup) - - if self == outgroup: - raise ValueError, "Cannot set myself as outgroup" - - parent_outgroup = outgroup.up - - # Detects (sub)tree root - n = outgroup - while n.up is not self: - n = n.up - - # If outgroup is a child from root, but with more than one - # sister nodes, creates a new node to group them - - self.children.remove(n) - if len(self.children) != 1: - down_branch_connector = self.__class__() - down_branch_connector.dist = 0.0 - down_branch_connector.support = n.support - for ch in self.get_children(): - down_branch_connector.children.append(ch) - ch.up = down_branch_connector - self.children.remove(ch) - else: - down_branch_connector = self.children[0] - - # Connects down branch to myself or to outgroup - quien_va_ser_padre = parent_outgroup - if quien_va_ser_padre is not self: - # Parent-child swapping - quien_va_ser_hijo = quien_va_ser_padre.up - quien_fue_padre = None - buffered_dist = quien_va_ser_padre.dist - buffered_support = quien_va_ser_padre.support - - while quien_va_ser_hijo is not self: - quien_va_ser_padre.children.append(quien_va_ser_hijo) - quien_va_ser_hijo.children.remove(quien_va_ser_padre) - - buffered_dist2 = quien_va_ser_hijo.dist - buffered_support2 = quien_va_ser_hijo.support - quien_va_ser_hijo.dist = buffered_dist - quien_va_ser_hijo.support = buffered_support - buffered_dist = buffered_dist2 - buffered_support = buffered_support2 - - quien_va_ser_padre.up = quien_fue_padre - quien_fue_padre = quien_va_ser_padre - - quien_va_ser_padre = quien_va_ser_hijo - quien_va_ser_hijo = quien_va_ser_padre.up - - quien_va_ser_padre.children.append(down_branch_connector) - down_branch_connector.up = quien_va_ser_padre - quien_va_ser_padre.up = quien_fue_padre - - down_branch_connector.dist += buffered_dist - outgroup2 = parent_outgroup - parent_outgroup.children.remove(outgroup) - outgroup2.dist = 0 - - else: - outgroup2 = down_branch_connector - - outgroup.up = self - outgroup2.up = self - # outgroup is always the first children. Some function my - # trust on this fact, so do no change this. - self.children = [outgroup,outgroup2] - middist = (outgroup2.dist + outgroup.dist)/2 - outgroup.dist = middist - outgroup2.dist = middist - outgroup2.support = outgroup.support - - def unroot(self): - """ - Unroots current node. This function is expected to be used on - the absolute tree root node, but it can be also be applied to - any other internal node. It will convert a split into a - multifurcation. - """ - # if is rooted - if not self.is_root(): - print >>sys.stderr, "Warning. You are unrooting an internal node.!!" - if len(self.children)==2: - if not self.children[0].is_leaf(): - self.children[0].delete() - elif not self.children[1].is_leaf(): - self.children[1].delete() - else: - raise TreeError, "Cannot unroot a tree with only two leaves" - - def show(self, layout=None, tree_style=None, name="ETE"): - """ - Starts an interative session to visualize current node - structure using provided layout and TreeStyle. - - """ - try: - from ete2.treeview import drawer - except ImportError, e: - print "'treeview' module could not be loaded.\n",e - print "\n\n" - print e - else: - drawer.show_tree(self, layout=layout, - tree_style=tree_style, win_name=name) - - def render(self, file_name, layout=None, w=None, h=None, \ - tree_style=None, units="px", dpi=90): - """ - Renders the node structure as an image. - - :var file_name: path to the output image file. valid - extensions are .SVG, .PDF, .PNG - - :var layout: a layout function or a valid layout function name - - :var tree_style: a `TreeStyle` instance containing the image - properties - - :var px units: "px": pixels, "mm": millimeters, "in": inches - :var None h: height of the image in :attr:`units` - :var None w: weight of the image in :attr:`units` - :var 300 dpi: dots per inches. - - """ - - try: - from ete2.treeview import drawer - except ImportError, e: - print "'treeview' module could not be loaded.\n",e - print "\n\n" - print e - else: - return drawer.render_tree(self, file_name, w=w, h=h, - layout=layout, tree_style=tree_style, - units=units, dpi=dpi) - - def copy(self, method="cpickle"): - """.. versionadded: 2.1 - - Returns a copy of the current node. - - :var cpickle method: Protocol used to copy the node - structure. The following values are accepted: - - - "newick": Tree topology, node names, branch lengths and - branch support values will be copied by as represented in - the newick string (copy by newick string serialisation). - - - "newick-extended": Tree topology and all node features - will be copied based on the extended newick format - representation. Only node features will be copied, thus - excluding other node attributes. As this method is also - based on newick serialisation, features will be converted - into text strings when making the copy. - - - "cpickle": The whole node structure and its content is - cloned based on cPickle object serialisation (slower, but - recommended for full tree copying) - - - "deepcopy": The whole node structure and its content is - copied based on the standard "copy" Python functionality - (this is the slowest method but it allows to copy complex - objects even if attributes point to lambda functions, - etc.) - - """ - if method=="newick": - new_node = self.__class__(self.write(features=["name"], format_root_node=True)) - elif method=="newick-extended": - self.write(features=[], format_root_node=True) - new_node = self.__class__(self.write(features=[])) - elif method == "deepcopy": - parent = self.up - self.up = None - new_node = copy.deepcopy(self) - self.up = parent - elif method == "cpickle": - parent = self.up - self.up = None - new_node = cPickle.loads(cPickle.dumps(self, 2)) - self.up = parent - else: - raise ValuerError("Invalid copy method") - - return new_node - - def _asciiArt(self, char1='-', show_internal=True, compact=False, attributes=None): - """ - Returns the ASCII representation of the tree. - - Code based on the PyCogent GPL project. - """ - if not attributes: - attributes = ["name"] - node_name = ', '.join(map(str, [getattr(self, v) for v in attributes if hasattr(self, v)])) - - LEN = max(3, len(node_name) if not self.children or show_internal else 3) - PAD = ' ' * LEN - PA = ' ' * (LEN-1) - if not self.is_leaf(): - mids = [] - result = [] - for c in self.children: - if len(self.children) == 1: - char2 = '/' - elif c is self.children[0]: - char2 = '/' - elif c is self.children[-1]: - char2 = '\\' - else: - char2 = '-' - (clines, mid) = c._asciiArt(char2, show_internal, compact, attributes) - mids.append(mid+len(result)) - result.extend(clines) - if not compact: - result.append('') - if not compact: - result.pop() - (lo, hi, end) = (mids[0], mids[-1], len(result)) - prefixes = [PAD] * (lo+1) + [PA+'|'] * (hi-lo-1) + [PAD] * (end-hi) - mid = (lo + hi) / 2 - prefixes[mid] = char1 + '-'*(LEN-2) + prefixes[mid][-1] - result = [p+l for (p,l) in zip(prefixes, result)] - if show_internal: - stem = result[mid] - result[mid] = stem[0] + node_name + stem[len(node_name)+1:] - return (result, mid) - else: - return ([char1 + '-' + node_name], 0) - - def get_ascii(self, show_internal=True, compact=False, attributes=None): - """ - Returns a string containing an ascii drawing of the tree. - - :argument show_internal: includes internal edge names. - :argument compact: use exactly one line per tip. - - :param attributes: A list of node attributes to shown in the - ASCII representation. - - """ - (lines, mid) = self._asciiArt(show_internal=show_internal, - compact=compact, attributes=attributes) - return '\n'+'\n'.join(lines) - - - def ladderize(self, direction=0): - """ - .. versionadded: 2.1 - - Sort the branches of a given tree (swapping children nodes) - according to the size of each partition. - - :: - - t = Tree("(f,((d, ((a,b),c)),e));") - - print t - - # - # /-f - # | - # | /-d - # ----| | - # | /---| /-a - # | | | /---| - # | | \---| \-b - # \---| | - # | \-c - # | - # \-e - - t.ladderize() - print t - - # /-f - # ----| - # | /-e - # \---| - # | /-d - # \---| - # | /-c - # \---| - # | /-a - # \---| - # \-b - - """ - - if not self.is_leaf(): - n2s = {} - for n in self.get_children(): - s = n.ladderize(direction=direction) - n2s[n] = s - - self.children.sort(lambda x,y: cmp(n2s[x], n2s[y])) - if direction == 1: - self.children.reverse() - size = sum(n2s.values()) - else: - size = 1 - - return size - - def sort_descendants(self): - """ - .. versionadded: 2.1 - - This function sort the branches of a given tree by - considerening node names. After the tree is sorted, nodes are - labeled using ascendent numbers. This can be used to ensure - that nodes in a tree with the same node names are always - labeled in the same way. Note that if duplicated names are - present, extra criteria should be added to sort nodes. - - Unique id is stored as a node._nid attribute - - """ - - node2content = self.get_cached_content() - def sort_by_content(x, y): - return cmp(str(sorted([i.name for i in node2content[x]])), - str(sorted([i.name for i in node2content[y]]))) - - for n in self.traverse(): - if not n.is_leaf(): - n.children.sort(sort_by_content) - return node2content - - def get_cached_content(self, store_attr=None, _store=None): - """ - .. versionadded: 2.2 - - Returns a dictionary pointing to the preloaded content of each - internal node under this tree. Such a dictionary is intended - to work as a cache for operations that require many traversal - operations. - - :param None store_attr: Specifies the node attribute that - should be cached (i.e. name, distance, etc.). When none, the - whole node instance is cached. - - :param _store: (internal use) - - """ - if _store is None: - _store = {} - - for ch in self.children: - ch.get_cached_content(store_attr=store_attr, _store=_store) - - if self.children: - val = set() - for ch in self.children: - val.update(_store[ch]) - _store[self] = val - else: - if store_attr is None: - val = self - else: - val = getattr(self, store_attr) - _store[self] = set([val]) - return _store - - def robinson_foulds(self, t2, attr_t1="name", attr_t2="name"): - """ - .. versionadded: 2.2 - - Returns the Robinson-Foulds symmetric distance between current - tree and a different tree instance. - - :param t2: target tree - - :param name attr_t1: Compare trees using a custom node - attribute as a node name. - - :param name attr_t2: Compare trees using a custom node - attribute as a node name in target tree. - - :returns: (symmetric distance, total partitions, common node - names, partitions in current tree, partitions in target tree) - - """ - - t1 = self - t1content = t1.get_cached_content() - t2content = t2.get_cached_content() - target_names = set([getattr(_n, attr_t1) for _n in t1content[t1]]) - ref_names = set([getattr(_n, attr_t2) for _n in t2content[t2]]) - common_names = target_names & ref_names - if len(common_names) < 2: - raise ValueError("Trees share less than 2 nodes") - - r1 = set([",".join(sorted([getattr(_c, attr_t1) for _c in cont - if getattr(_c, attr_t1) in common_names])) - for cont in t1content.values() if len(cont)>1]) - r2 = set([",".join(sorted([getattr(_c, attr_t2) for _c in cont - if getattr(_c, attr_t2) in common_names])) - for cont in t2content.values() if len(cont)>1]) - r1.discard("") - r2.discard("") - inters = r1.intersection(r2) - if len(r1) == len(r2): - rf = (len(r1) - len(inters)) * 2 - else : - rf = (len(r1) - len(inters)) + (len(r2) - len(inters)) - max_parts = len(r1) + len(r2) - return rf, max_parts, common_names, r1, r2 - - def get_partitions(self): - """ - .. versionadded: 2.1 - - It returns the set of all possible partitions under a - node. Note that current implementation is quite inefficient - when used in very large trees. - - t = Tree("((a, b), e);") - partitions = t.get_partitions() - - # Will return: - # a,b,e - # a,e - # b,e - # a,b - # e - # b - # a - """ - all_leaves = frozenset(self.get_leaf_names()) - all_partitions = set([all_leaves]) - for n in self.iter_descendants(): - p1 = frozenset(n.get_leaf_names()) - p2 = frozenset(all_leaves - p1) - all_partitions.add(p1) - all_partitions.add(p2) - return all_partitions - - def convert_to_ultrametric(self, tree_length, strategy="balanced"): - """ - .. versionadded: 2.1 - - Converts a tree to ultrametric topology (all leaves must have - the same distance to root). Note that, for visual inspection - of ultrametric trees, node.img_style["size"] should be set to - 0. - """ - - # pre-calculate how many splits remain under each node - node2max_depth = {} - for node in self.traverse("postorder"): - if not node.is_leaf(): - max_depth = max([node2max_depth[c] for c in node.children]) + 1 - node2max_depth[node] = max_depth - else: - node2max_depth[node] = 1 - node2dist = {self: 0.0} - tree_length = float(tree_length) - step = tree_length / node2max_depth[self] - for node in self.iter_descendants("levelorder"): - if strategy == "balanced": - node.dist = (tree_length - node2dist[node.up]) / node2max_depth[node] - node2dist[node] = node.dist + node2dist[node.up] - elif strategy == "fixed": - if not node.is_leaf(): - node.dist = step - else: - node.dist = tree_length - ((node2dist[node.up]) * step) - node2dist[node] = node2dist[node.up] + 1 - node.dist = node.dist - - def check_monophyly(self, values, target_attr, ignore_missing=False): - """ - Returns True if a given target attribute is monophyletic under - this node for the provided set of values. - - If not all values are represented in the current tree - structure, a ValueError exception will be raised to warn that - strict monophyly could never be reached (this behaviour can be - avoided by enabling the `ignore_missing` flag. - - :param values: a set of values for which monophyly is - expected. - - :param target_attr: node attribute being used to check - monophyly (i.e. species for species trees, names for gene - family trees, or any custom feature present in the tree). - - :param False ignore_missing: Avoid raising an Exception when - missing attributes are found. - """ - if type(values) != set: - values = set(values) - - # This is the only time I traverse the tree, then I use cached - # leaf content - n2leaves = self.get_cached_content() - # Locate leaves matching requested attribute values - targets = [leaf for leaf in n2leaves[self] - if getattr(leaf, target_attr) in values] - - # Raise an error if requested attribute values are not even present - if not ignore_missing: - missing_values = values - set([getattr(n, target_attr) for n - in targets]) - if missing_values: - raise ValueError("Expected '%s' value(s) not found: %s" %( - target_attr, ','.join(missing_values))) - - # Check monophyly with get_common_ancestor. Note that this - # step does not require traversing the tree again because - # targets are node instances instead of node names, and - # get_common_ancestor function is smart enough to detect it - # and avoid unnecessary traversing. - common = self.get_common_ancestor(targets) - observed = n2leaves[common] - foreign_leaves = [leaf for leaf in observed - if getattr(leaf, target_attr) not in values] - if not foreign_leaves: - return True, "monophyletic" - else: - # if the requested attribute is not monophyletic in this - # node, let's differentiate between poly and paraphyly. - poly_common = self.get_common_ancestor(foreign_leaves) - # if the common ancestor of all foreign leaves is self - # contained, we have a paraphyly. Otherwise, polyphyly. - polyphyletic = [leaf for leaf in poly_common if - getattr(leaf, target_attr) in values] - if polyphyletic: - return False, "polyphyletic" - else: - return False, "paraphyletic" - - - def get_monophyletic(self, values, target_attr): - """ - .. versionadded:: 2.2 - - Returns a list of nodes matching the provided monophyly - criteria. For a node to be considered a match, all - `target_attr` values within and node, and exclusively them, - should be grouped. - - :param values: a set of values for which monophyly is - expected. - - :param target_attr: node attribute being used to check - monophyly (i.e. species for species trees, names for gene - family trees). - - """ - - if type(values) != set: - values = set(values) - - n2values = self.get_cached_content(store_attr=target_attr) - - is_monophyletic = lambda node: n2values[node] == values - for match in self.iter_leaves(is_leaf_fn=is_monophyletic): - if is_monophyletic(match): - yield match - - - def resolve_polytomy(self, default_dist=0.0, default_support=0.0, - recursive=True): - """ - .. versionadded: 2.2 - - Resolve all polytomies under current node by creating an - arbitrary dicotomic structure among the affected nodes. This - function randomly modifies current tree topology and should - only be used for compatibility reasons (i.e. programs - rejecting multifurcated node in the newick representation). - - :param 0.0 default_dist: artificial branch distance of new - nodes. - - :param 0.0 default_support: artificial branch support of new - nodes. - - :param True recursive: Resolve any polytomy under this - node. When False, only current node will be checked and fixed. - """ - - - def _resolve(node): - if len(node.children) > 2: - children = list(node.children) - node.children = [] - next_node = root = node - for i in xrange(len(children)-2): - next_node = next_node.add_child() - next_node.dist = default_dist - next_node.support = default_support - - next_node = root - for ch in children: - next_node.add_child(ch) - if ch != children[-2]: - next_node = next_node.children[0] - target = [self] - if recursive: - target.extend([n for n in self.get_descendants()]) - for n in target: - _resolve(n) - - - def add_face(self, face, column, position="branch-right"): - """ - .. versionadded: 2.1 - - Add a fixed face to the node. This type of faces will be - always attached to nodes, independently of the layout - function. - - :argument face: a Face or inherited instance - :argument column: An integer number starting from 0 - :argument "branch-right" position: Posible values are: - "branch-right", "branch-top", "branch-bottom", "float", - "aligned" - """ - - if not hasattr(self, "_faces"): - self._faces = _FaceAreas() - - if position not in FACE_POSITIONS: - raise ValueError("face position not in %s" %FACE_POSITIONS) - - if isinstance(face, Face): - getattr(self._faces, position).add_face(face, column=column) - else: - raise ValueError("not a Face instance") - - def clear_face(self): - self._faces = _FaceAreas() - - def set_style(self, node_style): - """ - .. versionadded: 2.1 - - Set 'node_style' as the fixed style for the current node. - """ - if TREEVIEW: - if node_style is None: - node_style = NodeStyle() - if type(node_style) is NodeStyle: - self._img_style = node_style - else: - raise ValueError("Treeview module is disabled") - - def phonehome(self): - from ete2 import _ph - _ph.call() - -def _translate_nodes(root, *nodes): - name2node = dict([ [n, None] for n in nodes if type(n) is str]) - for n in root.traverse(): - if n.name in name2node: - if name2node[n.name] is not None: - raise ValueError, "Ambiguous node name: "+str(n.name) - else: - name2node[n.name] = n - - if None in name2node.values(): - notfound = [key for key, value in name2node.iteritems() if value is None] - raise ValueError("Node names not found: "+str(notfound)) - - valid_nodes = [] - for n in nodes: - if type(n) is not str: - if type(n) is not root.__class__ : - raise ValueError, "Invalid target node: "+str(n) - else: - valid_nodes.append(n) - - valid_nodes.extend(name2node.values()) - if len(valid_nodes) == 1: - return valid_nodes[0] - else: - return valid_nodes - - -def OLD_translate_nodes(root, *nodes): - target_nodes = [] - for n in nodes: - if type(n) is str: - mnodes = root.search_nodes(name=n) - if len(mnodes) == 0: - raise ValueError, "Node name not found: "+str(n) - elif len(mnodes)>1: - raise ValueError, "Ambiguous node name: "+str(n) - else: - target_nodes.append(mnodes[0]) - elif type(n) != root.__class__: - raise ValueError, "Invalid target node: "+str(n) - else: - target_nodes.append(n) - - if len(target_nodes) == 1: - return target_nodes[0] - else: - return target_nodes - -### R bindings -def asETE(R_phylo_tree): - try: - import rpy2.robjects as robjects - R = robjects.r - except ImportError, e: - print e - raise Exception ("RPy >= 2.0 is required to connect") - - R.library("ape") - return Tree( R["write.tree"](R_phylo_tree)[0]) - -def asRphylo(ETE_tree): - try: - import rpy2.robjects as robjects - R = robjects.r - except ImportError, e: - print e - raise Exception("RPy >= 2.0 is required to connect") - - R.library("ape") - return R['read.tree'](text=ETE_tree.write()) - -# Alias -#: .. currentmodule:: ete2 -Tree = TreeNode - - - - - diff --git a/ete2/coretype/tree.pyc b/ete2/coretype/tree.pyc deleted file mode 100644 index 97c25cf..0000000 Binary files a/ete2/coretype/tree.pyc and /dev/null differ diff --git a/ete2/evol/__init__.py b/ete2/evol/__init__.py deleted file mode 100644 index defcce3..0000000 --- a/ete2/evol/__init__.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#!/usr/bin/python -""" -06 Nov 2010 - -init of evol plugin -""" - -__author__ = "Francois-Jose Serra" -__email__ = "francois@barrabin.org" -__licence__ = "GPLv3" -__version__ = "0.0" - - -from parser.codemlparser import * -from evoltree import * -from model import Model -__all__ = evoltree.__all__ - - - diff --git a/ete2/evol/__init__.pyc b/ete2/evol/__init__.pyc deleted file mode 100644 index f7cb59a..0000000 Binary files a/ete2/evol/__init__.pyc and /dev/null differ diff --git a/ete2/evol/control.py b/ete2/evol/control.py deleted file mode 100644 index 69d5efe..0000000 --- a/ete2/evol/control.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#!/usr/bin/python -""" -Parameters for running codeml -""" - -__author__ = "Francois-Jose Serra" -__email__ = "francois@barrabin.org" -__licence__ = "GPLv3" -__version__ = "0.0" - - -PARAMS = { - 'seqfile' : 'algn', - 'treefile' : 'tree', - 'outfile' : 'out', - 'noisy' : 0, - 'verbose' : 2, - 'runmode' : 0, - 'seqtype' : 1, - 'CodonFreq' : 2, - 'clock' : 0, - 'aaDist' : 0, - 'model' : 0, - 'NSsites' : 2, - 'icode' : 0, - 'Mgene' : 0, - 'fix_kappa' : 0, - 'kappa' : 2, - 'ndata' : '*10', - 'fix_omega' : 0, - 'omega' : 0.7, - 'fix_alpha' : 1, - 'alpha' : 0., # if 0 -> infinity - 'Malpha' : 0, - 'ncatG' : 8, - 'getSE' : 0, - 'RateAncestor' : 0, - 'fix_blength' : 0, - 'Small_Diff' : '1e-6', - 'cleandata' : 0, - 'method' : 0 - } - -AVAIL = { - 'M0' : {'typ': 'null' , 'evol': 'negative-selection', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 0), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M1' : {'typ': 'site' , 'evol': 'relaxation', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 1), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M2' : {'typ': 'site' , 'evol': 'positive-selection', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 2), - ('omega' , 1.7), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M3' : {'typ': 'site' , 'evol': 'discrete', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 3), - ('omega' , .7), - ('ncatG' , 3), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M4' : {'typ': 'site' , 'evol': 'frequencies', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 4), - ('omega' , .7), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M5' : {'typ': 'site' , 'evol': 'gamma', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 5), - ('omega' , .7), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M6' : {'typ': 'site' , 'evol': '2 gamma', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 5), - ('omega' , .7), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M7' : {'typ': 'site' , 'evol': 'relaxation', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 7), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M8a' : {'typ': 'site' , 'evol': 'relaxation', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 8), - ('fix_omega' , 1), - ('omega' , 1), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M8' : {'typ': 'site' , 'evol': 'positive-selection', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 8), - ('omega' , 1.7), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M9' : {'typ': 'site' , 'evol': 'beta and gamma', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 9), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M10' : {'typ': 'site' , 'evol': 'beta and gamma + 1', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 10), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M11' : {'typ': 'site' , 'evol': 'beta and normal > 1', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 11), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M12' : {'typ': 'site' , 'evol': '0 and 2 normal > 2', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 12), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'M13' : {'typ': 'site' , 'evol': '3 normal > 0', - 'exec': 'codeml', - 'allow_mark': False, - 'changes': [('NSsites' , 13), - ('alpha' , '*'), - ('method' , '*'), - ('Malpha' , '*'), - ('fix_alpha' , '*')]}, - 'fb' : {'typ': 'branch' , 'evol': 'free-ratios', - 'exec': 'codeml', - 'allow_mark': False , - 'changes': [('model' , 1), - ('NSsites' , 0)]}, - 'fb_anc': {'typ': 'branch_ancestor' , 'evol': 'free-ratios', - 'exec': 'codeml', - 'allow_mark': False , - 'changes': [('model' , 1), - ('RateAncestor', 1), - ('NSsites' , 0)]}, - 'b_free': {'typ': 'branch' , 'evol': 'positive-selection', - 'exec': 'codeml', - 'allow_mark': True , - 'changes': [('model' , 2), - ('NSsites' , 0)]}, - 'b_neut': {'typ': 'branch' , 'evol': 'relaxation', - 'exec': 'codeml', - 'allow_mark': True , - 'changes': [('model' , 2), - ('NSsites' , 0), - ('fix_omega' , 1), - ('omega' , 1)]}, - 'bsA1' : {'typ': 'branch-site', 'evol': 'relaxation', - 'exec': 'codeml', - 'allow_mark': True , - 'changes': [('model' , 2), - ('NSsites' , 2), - ('fix_omega' , 1), - ('omega' , 1), - ('ncatG' , '*')]}, - 'bsA' : {'typ': 'branch-site', 'evol': 'positive-selection', - 'exec': 'codeml', - 'allow_mark': True , - 'changes': [('model' , 2), - ('NSsites' , 2), - ('omega' , 1.7), - ('ncatG' , '*')]}, - 'bsB' : {'typ': 'branch-site', 'evol': 'positive-selection', - 'exec': 'codeml', - 'allow_mark': True , - 'changes': [('model' , 2), - ('NSsites' , 3), - ('omega' , 1.7), - ('ncatG' , '*')]}, - 'bsC' : {'typ': 'branch-site', 'evol': 'different-ratios', - 'exec': 'codeml', - 'allow_mark': True , - 'changes': [('model' , 3), - ('NSsites' , 2), - ('ncatG' , 3)]}, - 'bsD' : {'typ': 'branch-site', 'evol': 'different-ratios', - 'exec': 'codeml', - 'allow_mark': True , - 'changes': [('model' , 3), - ('NSsites' , 3), - ('ncatG' , 3)]}, - 'SLR' : {'typ' : 'site', 'evol': 'positive/negative selection', - 'exec': 'Slr', - 'sep' : '= ', - 'allow_mark': False , - 'changes': map (lambda x: (x[0], '*'), - filter (lambda x: 'file' not in x[0], - PARAMS.items())) + \ - [('positive_only', '0')]} - } - diff --git a/ete2/evol/control.pyc b/ete2/evol/control.pyc deleted file mode 100644 index df1d23b..0000000 Binary files a/ete2/evol/control.pyc and /dev/null differ diff --git a/ete2/evol/evoltree.py b/ete2/evol/evoltree.py deleted file mode 100644 index 470302c..0000000 --- a/ete2/evol/evoltree.py +++ /dev/null @@ -1,542 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#!/usr/bin/python -""" -this module defines the EvolNode dataytype to manage evolutionary -variables and integrate them within phylogenetic trees. It inheritates -the coretype PhyloNode and add some speciall features to the the node -instances. -""" - -__author__ = "Francois-Jose Serra" -__email__ = "francois@barrabin.org" -__licence__ = "GPLv3" -__version__ = "0.0" -__references__ = ''' -Yang, Z., Nielsen, R., Goldman, N., & Pedersen, A. M. 2000. - Codon-substitution models for heterogeneous selection pressure at amino acid sites. - Genetics 155: 431-49. - Retrieved from http://www.pubmedcentral.nih.gov/articlerender.fcgi?artid=1461088&tool=pmcentrez&rendertype=abstract -Yang, Z., & Nielsen, R. 2002. - Codon-substitution models for detecting molecular adaptation at individual sites along specific lineages. - Molecular biology and evolution 19: 908-17. - Retrieved from http://www.ncbi.nlm.nih.gov/pubmed/12032247 -Bielawski, J. P., & Yang, Z. 2004. - A maximum likelihood method for detecting functional divergence at individual codon sites, with application to gene family evolution. - Journal of molecular evolution 59: 121-32. - Retrieved from http://www.ncbi.nlm.nih.gov/pubmed/15383915 -Zhang, J., Nielsen, R., & Yang, Z. 2005. - Evaluation of an improved branch-site likelihood method for detecting positive selection at the molecular level. - Molecular biology and evolution 22: 2472-9. - Retrieved from http://www.ncbi.nlm.nih.gov/pubmed/16107592 -Yang, Z. 2007. - PAML 4: phylogenetic analysis by maximum likelihood. - Molecular biology and evolution 24: 1586-91. - Retrieved from http://www.ncbi.nlm.nih.gov/pubmed/17483113 -''' - -import os -from warnings import warn - -from ete2 import PhyloNode -from ete2 import SeqGroup -from ete2.evol.model import Model, PARAMS, AVAIL -from ete2.evol.utils import translate -from ete2.parser.newick import write_newick -try: - from ete2.treeview import TreeStyle -except ImportError: - TREEVIEW = False -else: - TREEVIEW = True - -__all__ = ["EvolNode", "EvolTree"] - -def _parse_species(name): - ''' - just to return specie name from fasta description - ''' - return name[:3] - -class EvolNode(PhyloNode): - """ Re-implementation of the standart TreeNode instance. It adds - attributes and methods to work with phylogentic trees. - - :argument newick: path to tree in newick format, can also be a string - :argument alignment: path to alignment, can also be a string. - :argument fasta alg_format: alignment format. - :argument sp_naming_function: function to infer species name. - :argument format: type of newick format - :argument binpath: path to binaries, in case codeml or SLR are not in global path. - - """ - - def __init__(self, newick=None, alignment=None, alg_format="fasta", - sp_naming_function=_parse_species, format=0, - binpath=''): - ''' - freebranch: path to find codeml output of freebranch model. - ''' - # _update names? - self.workdir = '/tmp/ete2-tmp/' - self.execpath = binpath - self._models = {} - - PhyloNode.__init__(self, newick=newick, format=format, - sp_naming_function=sp_naming_function) - - if newick: - self._label_as_paml() - # initialize node marks - self.mark_tree([]) - - - def _label_internal_nodes(self, nid=None): - """ - nid needs to be a list in order to keep count through recursivity - """ - for node in self.get_children(): - if node.is_leaf(): - continue - nid[0] += 1 - node.add_feature('node_id', nid[0]) - node._label_internal_nodes(nid) - - def _label_as_paml(self): - ''' - to label tree as paml, nearly walking man over the tree algorithm - WARNING: sorted names in same order that sequence - WARNING: depends on tree topology conformation, not the same after a swap - activates the function get_descendants_by_pamlid - ''' - nid = 1 - # check we do not have dupplicated names in tree - if (len(self)) != len(set(self.get_leaf_names())): - duplis = [n for n in self.get_leaf_names() if self.get_leaf_names().count(n)>1] - raise Exception('EvolTree require unique names for leaves', duplis) - # put ids - for leaf in sorted(self, key=lambda x: x.name): - leaf.add_feature ('node_id', nid) - nid += 1 - self.add_feature('node_id', nid) - self._label_internal_nodes([nid]) - - def get_descendant_by_node_id(self, idname): - ''' - returns node list corresponding to a given idname - ''' - try: - for n in self.iter_descendants(): - if n.node_id == idname: - return n - if self.node_id == idname: - return self - except AttributeError: - warn('Should be first labelled as paml ' + \ - '(automatically done when alignemnt is loaded)') - - def __write_algn(self, fullpath): - """ - to write algn in paml format - """ - seq_group = SeqGroup() - for n in self: - seq_group.id2seq [n.node_id] = n.nt_sequence - seq_group.id2name [n.node_id] = n.name - seq_group.name2id [n.name ] = n.node_id - seq_group.write(outfile=fullpath, format='paml') - - - def run_model(self, model_name, ctrl_string='', keep=True, **kwargs): - ''' - To compute evolutionnary models. e.g.: b_free_lala.vs.lele, will launch one free branch model, and store - it in "WORK_DIR/b_free_lala.vs.lele" directory - - WARNING: this functionality needs to create a working directory in "rep" - - WARNING: you need to have codeml and/or SLR in your path - - The models available are: - - =========== ============================= ================== - Model name Description Model kind - =========== ============================= ==================\n%s - =========== ============================= ==================\n - - :argument model_name: a string like "model-name[.some-secondary-name]" (e.g.: "fb.my_first_try", or just "fb") - * model-name is compulsory, is the name of the model (see table above for the full list) - * the second part is accessory, it is to avoid over-writing models with the same name. - :argument ctrl_string: list of parameters that can be used as control file. - :argument kwargs: extra parameters should be one of: %s. - ''' - from subprocess import Popen, PIPE - model_obj = Model(model_name, self, **kwargs) - fullpath = os.path.join (self.workdir, model_obj.name) - os.system("mkdir -p %s" %fullpath) - # write tree file - self.__write_algn(fullpath + '/algn') - if model_obj.properties['exec'] == 'Slr': - self.write(outfile=fullpath+'/tree', - format = (11)) - else: - self.write(outfile=fullpath+'/tree', - format = (10 if model_obj.properties['allow_mark'] else 9)) - # write algn file - ## MODEL MODEL MDE - if ctrl_string == '': - ctrl_string = model_obj.get_ctrl_string(fullpath+'/tmp.ctl') - else: - open(fullpath+'/tmp.ctl', 'w').write(ctrl_string) - hlddir = os.getcwd() - os.chdir(fullpath) - bin = os.path.join(self.execpath, model_obj.properties['exec']) - try: - proc = Popen([bin, 'tmp.ctl'], stdout=PIPE) - except OSError: - raise Exception(('ERROR: {} not installed, ' + - 'or wrong path to binary\n').format(bin)) - run, err = proc.communicate() - if err is not None: - warn("ERROR: codeml not found!!!\n" + - " define your variable EvolTree.execpath") - return 1 - if 'error' in run or 'Error' in run: - warn("ERROR: inside codeml!!\n" + run) - return 1 - os.chdir(hlddir) - if keep: - setattr(model_obj, 'run', run) - self.link_to_evol_model(os.path.join(fullpath,'out'), model_obj) - sep = '\n' - run_model.__doc__ = run_model.__doc__ % \ - (sep.join(map(lambda x: \ - ' %-8s %-27s %-15s ' % \ - ('%s' % (x), AVAIL[x]['evol'], AVAIL[x]['typ']), - sorted (sorted (AVAIL.keys()), cmp=lambda x, y : \ - cmp(AVAIL[x]['typ'], AVAIL[y]['typ']), - reverse=True))), - ', '.join(PARAMS.keys())) - - - #def test_codon_model(self): - # for c_frq in range(4): - # self.run_model('M0.model_test-'+str(c_frq), CodonFreq=c_frq) - # if self.get_most_likely('M0.model_test-1', 'M0.model_test-0') > 0.05: - # - # self.get_most_likely('M0.model_test-2', 'M0.model_test-0') - # self.get_most_likely('M0.model_test-3', 'M0.model_test-0') - # self.get_most_likely('M0.model_test-2', 'M0.model_test-1') - # self.get_most_likely('M0.model_test-3', 'M0.model_test-1') - # self.get_most_likely('M0.model_test-3', 'M0.model_test-2') - - def link_to_alignment(self, alignment, alg_format="paml", - nucleotides=True, **kwargs): - ''' - same function as for phyloTree, but translate sequences if nucleotides - nucleotidic sequence is kept under node.nt_sequence - - :argument alignment: path to alignment or string - :argument alg_format: one of fasta phylip or paml - :argument True alignment: set to False in case we want to keep it untranslated - - ''' - super(EvolTree, self).link_to_alignment(alignment, - alg_format=alg_format, **kwargs) - check_len = 0 - for leaf in self.iter_leaves(): - seq_len = len(str(leaf.sequence)) - if check_len and check_len != seq_len: - warn('WARNING: sequences with different lengths found!') - check_len = seq_len - leaf.nt_sequence = str(leaf.sequence) - if nucleotides: - leaf.sequence = translate(leaf.nt_sequence) - - def show(self, layout=None, tree_style=None, histfaces=None): - ''' - call super show of PhyloTree - histface should be a list of models to be displayes as histfaces - - :argument layout: a layout function - :argument None tree_style: tree_style object - :argument Nonehistface: an histogram face function. This is only to plot selective pressure among sites - - ''' - if TREEVIEW: - if not tree_style: - ts = TreeStyle() - else: - ts = tree_style - if histfaces: - for hist in histfaces: - try: - mdl = self.get_evol_model(hist) - except AttributeError: - warn('model %s not computed' % (hist)) - if not 'histface' in mdl.properties: - if len(histfaces)>1 and histfaces.index(hist)!=0: - mdl.set_histface(up=False) - else: - mdl.set_histface() - if mdl.properties ['histface'].up: - ts.aligned_header.add_face( - mdl.properties['histface'], 1) - else: - ts.aligned_foot.add_face( - mdl.properties['histface'], 1) - super(EvolTree, self).show(layout=layout, tree_style=ts) - else: - raise ValueError("Treeview module is disabled") - - - def render(self, file_name, layout=None, w=None, h=None, - tree_style=None, header=None, histfaces=None): - ''' - call super show adding up and down faces - - :argument layout: a layout function - :argument None tree_style: tree_style object - :argument Nonehistface: an histogram face function. This is only to plot selective pressure among sites - - ''' - if TREEVIEW: - if not tree_style: - ts = TreeStyle() - else: - ts = tree_style - if histfaces: - for hist in histfaces: - try: - mdl = self.get_evol_model(hist) - except AttributeError: - warn('model %s not computed' % (hist)) - if not 'histface' in mdl.properties: - if len(histfaces)>1 and histfaces.index(hist)!=0: - mdl.set_histface(up=False) - else: - mdl.set_histface() - if mdl.properties ['histface'].up: - ts.aligned_header.add_face( - mdl.properties['histface'], 1) - else: - ts.aligned_foot.add_face( - mdl.properties['histface'], 1) - return super(EvolTree, self).render(file_name, layout=layout, - tree_style=ts, - w=w, h=h) - else: - raise ValueError("Treeview module is disabled") - - def mark_tree(self, node_ids, verbose=False, **kargs): - ''' - function to mark branches on tree in order that paml could interpret it. - takes a "marks" argument that should be a list of #1,#1,#2 - e.g.: - :: - - t=Tree.mark_tree([2,3], marks=["#1","#2"]) - - :argument node_ids: list of node ids (have a look to node.node_id) - :argument False verbose: warn if marks do not correspond to codeml standard - :argument kargs: mainly for the marks key-word which needs a list of marks (marks=['#1', '#2']) - - ''' - from re import match - node_ids = map (int , node_ids) - if kargs.has_key('marks'): - marks = list(kargs['marks']) - else: - marks = ['#1']*len (node_ids) - for node in self.traverse(): - if not hasattr(node, 'node_id'): - continue - if node.node_id in node_ids: - if ('.' in marks[node_ids.index(node.node_id)] or \ - match('#[0-9]+', \ - marks[node_ids.index(node.node_id)])==None)\ - and verbose: - warn('WARNING: marks should be "#" sign directly '+\ - 'followed by integer\n' + self.mark_tree.func_doc) - node.add_feature('mark', ' '+marks[node_ids.index(node.node_id)]) - elif not 'mark' in node.features: - node.add_feature('mark', '') - - def link_to_evol_model(self, path, model): - ''' - link EvolTree to evolutionary model - * free-branch model ('fb') will append evol values to tree - * Site models (M0, M1, M2, M7, M8) will give evol values by site - and likelihood - - :argument path: path to outfile containing model computation result - :argument model: either the name of a model, or a Model object (usually empty) - - ''' - if type(model) == str : - model = Model(model, self, path) - else: - model._load(path) - # new entry in _models dict - while self._models.has_key(model.name): - model.name = model.name.split('__')[0] + str( - (int(model.name.split('__')[1]) - +1) if '__' in model.name else 0) - self._models[model.name] = model - if not os.path.isfile(path): - warn("ERROR: not a file: " + path) - return 1 - if len(self._models) == 1 and model.properties['exec']=='codeml': - self.change_dist_to_evol('bL', model, fill=True) - - def get_evol_model(self, modelname): - ''' - returns one precomputed model - - :argument modelname: string of the name of a model object stored - :returns: Model object - ''' - try: - return self._models [modelname] - except KeyError: - warn("Model %s not found." % (modelname)) - - - def write(self, features=None, outfile=None, format=10): - """ - Inherits from Tree but adds the tenth format, that allows to display marks for CodeML. - TODO: internal writting format need to be something like 0 - """ - from re import sub - if int(format)==11: - nwk = ' %s 1\n' % (len(self)) - nwk += sub('\[&&NHX:mark=([ #0-9.]*)\]', r'\1', \ - write_newick(self, features=['mark'],format=9)) - elif int(format)==10: - nwk = sub('\[&&NHX:mark=([ #0-9.]*)\]', r'\1', \ - write_newick(self, features=['mark'],format=9)) - else: - nwk = write_newick(self, features=features,format=format) - if outfile is not None: - open(outfile, "w").write(nwk) - return nwk - else: - return nwk - write.__doc__ += super(PhyloNode, PhyloNode()).write.__doc__.replace('argument format', - 'argument 10 format') - - - def get_most_likely(self, altn, null): - ''' - Returns pvalue of LRT between alternative model and null model. - - usual comparison are: - - ============ ======= =========================================== - Alternative Null Test - ============ ======= =========================================== - M2 M1 PS on sites (M2 prone to miss some sites) - (Yang 2000) - M3 M0 test of variability among sites - M8 M7 PS on sites - (Yang 2000) - M8 M8a RX on sites?? think so.... - bsA bsA1 PS on sites on specific branch - (Zhang 2005) - bsA M1 RX on sites on specific branch - (Zhang 2005) - bsC M1 different omegas on clades branches sites - ref: Yang Nielsen 2002 - bsD M3 different omegas on clades branches sites - (Yang Nielsen 2002, Bielawski 2004) - b_free b_neut foreground branch not neutral (w != 1) - - RX if P<0.05 (means that w on frg=1) - - PS if P>0.05 and wfrg>1 - - CN if P>0.05 and wfrg>1 - (Yang Nielsen 2002) - b_free M0 different ratio on branches - (Yang Nielsen 2002) - ============ ======= =========================================== - - :argument altn: model with higher number of parameters (np) - :argument null: model with lower number of parameters (np) - - ''' - altn = self.get_evol_model(altn) - null = self.get_evol_model(null) - if null.np > altn.np: - warn("first model should be the alternative, change the order") - return 1.0 - try: - if hasattr(altn, 'lnL') and hasattr(null, 'lnL'): - from ete2.evol.utils import chi_high - return chi_high(2*(altn.lnL - null.lnL), - df=(altn.np - null.np)) - else: - return 1 - except KeyError: - warn("at least one of %s or %s, was not calculated" % (altn.name, - null.name)) - exit(self.get_most_likely.func_doc) - - def change_dist_to_evol(self, evol, model, fill=False): - ''' - change dist/branch length of the tree to a given evolutionary - variable (dN, dS, w or bL), default is bL. - - :argument evol: evolutionary variable - :argument model: Model object from which to retrieve evolutionary variables - :argument False fill: do not affects only dist parameter, each node will be annotated with all evolutionary variables (nodel.dN, node.w...). - ''' - # branch-site outfiles do not give specific branch info - if not model.branches: - return - for node in self.iter_descendants(): - if not evol in model.branches[node.node_id]: - continue - node.dist = model.branches[node.node_id][evol] - if fill: - for e in ['dN', 'dS', 'w', 'bL']: - node.add_feature(e, model.branches [node.node_id][e]) - - -# cosmetic alias -EvolTree = EvolNode - diff --git a/ete2/evol/evoltree.pyc b/ete2/evol/evoltree.pyc deleted file mode 100644 index 91267e6..0000000 Binary files a/ete2/evol/evoltree.pyc and /dev/null differ diff --git a/ete2/evol/model.py b/ete2/evol/model.py deleted file mode 100644 index e37b7da..0000000 --- a/ete2/evol/model.py +++ /dev/null @@ -1,339 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#!/usr/bin/python -""" -this module defines the evolutionary Model that can be linked -to phylogeny, and computed by one of codeml, gerp, slr. -""" - -__author__ = "Francois-Jose Serra" -__email__ = "francois@barrabin.org" -__licence__ = "GPLv3" -__version__ = "0.0" - -from re import sub -from warnings import warn - -from ete2.evol.control import PARAMS, AVAIL -from ete2.evol.parser import parse_paml, parse_rst, get_ancestor, parse_slr -try: - from ete2.treeview.faces import SequencePlotFace -except ImportError: - TREEVIEW = False -else: - TREEVIEW = True - -class Model: - '''Evolutionary model. - "omega" stands for starting value of omega, in the computation. As - Zihen Yang says, it is good to try with different starting values... - model linked to tree by _tree variable - results of calculation are stored in dictionaries: - * branches: w dN dS bL by mean of their node_id - * sites : values at each site. - * classes : classes of sites and proportions - * stats : lnL number of parameters kappa value and codon frequencies stored here. - - available models are: - =========== ============================= ================== - Model name Description Model kind - =========== ============================= ==================\n%s - =========== ============================= ==================\n - - :argument model_name: string with model name. Add a dot followed by anything at the end of the string in order to extend the name of the model and avoid overwriting. - :argument None tree: a Tree object - :argument None path: path to outfile, were model computation output can be found. - - ''' - def __init__(self, model_name, tree=None, path=None, **kwargs): - self._tree = tree - self.name, args = check_name(model_name) - self.sites = None - self.classes = None - self.branches = {} - self.stats = {} - self.properties = {} - for a, b in args.items(): - self.properties [a] = b - params = dict(PARAMS.items()) - for key, arg in kwargs.items(): - if not params.has_key(key): - warn('WARNING: unknown param %s, can cause problems...'% (key)) - if key == 'gappy': - arg = not arg - params[key] = arg - self._change_params(params) - self.__check_marks() - if path: - self._load(path) - - def __str__(self): - ''' - to print nice info - ''' - str_mark = '' - str_line = '\n mark:%-5s, omega: %-10s, node_ids: %-4s, name: %s' - for i, node in enumerate(self._tree.traverse()): - if node.is_root(): - str_mark += str_line % (self.branches[node.node_id]['mark'], - 'None', - node.node_id, node.name or 'ROOT') - else: - str_mark += str_line % (self.branches[node.node_id]['mark'], - self.branches[node.node_id].get('w', - 'None'), - node.node_id, node.name or 'EDGE') - str_site = '' - str_line = '\n %-12s: %s ' - if self.classes: - for t in [t for t in self.classes]: - str_site += str_line % (t, ' '.join(['%s%s=%-9s' % (t[0], j, i)\ - for j, i in \ - enumerate(self.classes[t])] - )) - return ''' Evolutionary Model %s: - log likelihood : %s - number of parameters : %s - sites inference : %s - sites classes : %s - branches : %s - ''' % (self.name, - self.lnL if 'lnL' in self.stats else 'None', - self.np if 'np' in self.stats else 'None', - ', '.join(self.sites.keys()) if self.sites else 'None', - str_site if self.classes else 'None', - str_mark if self.branches else 'None' - ) - - - def __check_marks(self): - """ - checks if tree is marked and if model allows marks. - fill up branches dict with marks - """ - has_mark = any([n.mark for n in self._tree.iter_descendants()]) - for i, node in enumerate(self._tree.traverse()): - #if node.is_root(): continue - if has_mark and self.properties['allow_mark']: - self.branches[node.node_id] = {'mark': node.mark or ' #0'} - elif 'branch' in self.properties['typ']: - self.branches[node.node_id] = {'mark': ' #'+str(i)} - else: - self.branches[node.node_id] = {'mark': ''} - - def _load(self, path): - ''' - parse outfiles and load in model object - ''' - if self.properties['exec'] == 'codeml': - parse_paml(path, self) - # parse rst file if site or branch-site model - if 'site' in self.properties['typ']: - # sites and classes attr - for key, val in parse_rst(path).iteritems(): - setattr(self, key, val) - if 'ancestor' in self.properties['typ']: - get_ancestor(path, self) - vars(self) ['lnL'] = self.stats ['lnL'] - vars(self) ['np'] = self.stats ['np'] - elif self.properties['exec'] == 'Slr': - for key, val in parse_slr (path).iteritems(): - setattr (self, key, val) - vars(self) ['lnL'] = 0 - vars(self) ['np'] = 0 - - def _change_params(self, params): - ''' - change model specific values - ''' - for key, change in self.properties ['changes']: - params[key] = change - self.properties ['params'] = params - - def set_histface(self, up=True, hlines=(1.0, 0.3), kind='bar', - errors=False, colors=None, **kwargs): - ''' - To add histogram face for a given site mdl (M1, M2, M7, M8) - can choose to put it up or down the tree. - 2 types are available: - * hist: to draw histogram. - * line: to draw plot. - You can define color scheme by passing a diccionary, default is: - col = {'NS' : 'grey' , - 'RX' : 'green' , - 'RX+': 'green' , - 'CN' : 'cyan' , - 'CN+': 'blue' , - 'PS' : 'orange', - 'PS+': 'red' } - ''' - if self.sites == None: - warn("WARNING: model %s not computed." % (self.name)) - return None - if not 'header' in kwargs: - kwargs['header'] = 'Omega value for sites under %s model' % \ - (self.name) - if self.sites.has_key('BEB'): - val = 'BEB' - elif self.sites.has_key('NEB'): - val = 'NEB' - else: - val = 'SLR' - colors = colorize_rst(self.sites [val]['pv'], self.name, - self.sites[val]['class'], col=colors) - if not 'ylim' in kwargs: - kwargs['ylim'] = (0, 2) - if errors: - errors = self.sites[val]['se'] if self.sites[val].has_key('se')\ - else None - if TREEVIEW: - hist = SequencePlotFace(self.sites[val]['w'], hlines=hlines, - colors=colors, errors=errors, - ylabel=u'Omega (\u03c9)', kind=kind, - **kwargs) - if up: - setattr(hist, 'up', True) - else: - setattr(hist, 'up', False) - else: - hist = None - self.properties['histface'] = hist - - - def get_ctrl_string(self, outfile=None): - ''' - generate ctrl string to write to a file, if file is given, - write it, otherwise returns the string - - :argument None outfile: if a path is given here, write control string into it. - - :returns: the control string - - ''' - string = '' - if self.properties.has_key('sep'): - sep = self.properties ['sep'] - else: - sep = ' = ' - for prm in ['seqfile', 'treefile', 'outfile']: - string += '%15s%s%s\n' % (prm, sep, - str(self.properties['params'][prm])) - string += '\n' - for prm in sorted(self.properties ['params'].keys(), cmp=lambda x, y: \ - cmp(sub('fix_', '', x.lower()), - sub('fix_', '', y.lower()))): - if prm in ['seqfile', 'treefile', 'outfile']: - continue - if str(self.properties ['params'][prm]).startswith('*'): - continue - #string += ' *'+'%13s = %s\n' \ - # % (p, str(self.properties ['params'][p])[1:]) - else: - string += '%15s%s%s\n' % (prm, sep, - str(self.properties ['params'][prm])) - if outfile == None: - return string - else: - open(outfile, 'w').write(string) - -def check_name(model): - ''' - check that model name corresponds to one of the available - ''' - if AVAIL.has_key(sub('\..*', '', model)): - return model, AVAIL [sub('\..*', '', model)] - - - -def colorize_rst(vals, winner, classes, col=None): - ''' - Colorize function, that take in argument a list of values - corresponding to a list of classes and returns a list of - colors to paint histogram. - ''' - col = col or {'NS' : 'grey', - 'RX' : 'green', - 'RX+': 'green', - 'CN' : 'cyan', - 'CN+': 'blue', - 'PS' : 'orange', - 'PS+': 'red'} - colors = [] - for i in xrange(0, len(vals)): - class1 = classes[i] #int(sub('\/.*', '', sub('\(', '', classes[i]))) - class2 = max(classes)# int(sub('.*\/', '', sub('\)', '', classes[i]))) - pval = float(vals[i]) - if pval < 0.95: - colors.append(col['NS']) - elif (class1 not in [class2, 1]) and (winner in ['M2', 'M8', 'SLR']): - if pval < 0.99: - colors.append(col['RX']) - else: - colors.append(col['RX+']) - elif class1 == 1: - if pval < 0.99: - colors.append(col['CN']) - else: - colors.append(col['CN+']) - elif class1 == class2 and (winner in ['M2', 'M8', 'SLR']): - if pval < 0.99: - colors.append(col['PS']) - else: - colors.append(col['PS+']) - elif class1 == class2: - if pval < 0.99: - colors.append(col['RX']) - else: - colors.append(col['RX+']) - else: - colors.append(col['NS']) - return colors - - - -Model.__doc__ = Model.__doc__ % \ - ('\n'.join([ ' %-8s %-27s %-15s ' % \ - ('%s' % (x), AVAIL[x]['evol'], AVAIL[x]['typ']) \ - for x in sorted(sorted(AVAIL.keys()), - cmp=lambda x, y: \ - cmp(AVAIL[x]['typ'], - AVAIL[y]['typ']), - reverse=True)])) diff --git a/ete2/evol/model.pyc b/ete2/evol/model.pyc deleted file mode 100644 index 966bada..0000000 Binary files a/ete2/evol/model.pyc and /dev/null differ diff --git a/ete2/evol/parser/__init__.py b/ete2/evol/parser/__init__.py deleted file mode 100644 index 1c792e0..0000000 --- a/ete2/evol/parser/__init__.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#!/usr/bin/python -# Author: Francois-Jose Serra -# Creation Date: 2010/11/03 21:20:05 - -from codemlparser import * -from slrparser import * diff --git a/ete2/evol/parser/__init__.pyc b/ete2/evol/parser/__init__.pyc deleted file mode 100644 index 3593dcb..0000000 Binary files a/ete2/evol/parser/__init__.pyc and /dev/null differ diff --git a/ete2/evol/parser/codemlparser.py b/ete2/evol/parser/codemlparser.py deleted file mode 100644 index 1ffcc7d..0000000 --- a/ete2/evol/parser/codemlparser.py +++ /dev/null @@ -1,328 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#!/usr/bin/python -""" -ugly parsers for outfiles of codeml, rst file for sites, -and main outfile -""" - -__author__ = "Francois-Jose Serra" -__email__ = "francois@barrabin.org" -__licence__ = "GPLv3" -__version__ = "0.0" - -import re -from warnings import warn - -def parse_rst (path): - ''' - parse rst files from codeml, all site, branch-site models. - return 2 dicts "classes" of sites, and values at each site "sites" - ''' - typ = None - classes = {} - sites = {} - k = 0 - i = 0 - path = '/'.join (path.split('/')[:-1]) + '/rst' - for line in open (path): - # get number of classes of sites - if line.startswith ('dN/dS '): - k = int (re.sub ('.* \(K=([0-9]+)\)\n', '\\1', line)) - continue - # get values of omega and proportions - if typ is None and \ - re.match ('^[a-z]+.*(\d+\.\d{5} *){'+ str(k) +'}', line): - var = re.sub (':', '', line.split(' ')[0]) - if var.startswith ('p'): - var = 'proportions' - classes [var] = re.findall ('\d+\.\d{5}', line) - continue - # parse NEB and BEB tables - if '(BEB)' in line : - k = int (re.sub ('.*for (\d+) classes .*\n', '\\1', line)) - typ = 'BEB' - sites [typ] = {} - continue - if '(NEB)' in line : - typ = 'NEB' - sites [typ] = {} - continue - # at the end of some BEB/NEB tables: - if line.startswith ('Positively '): - typ = None - # continue if we are not in table - if not re.match ('^ *[0-9]+ [A-Z*-] ', line) or typ == None: - continue - # line to list - line = line.replace(' +- ', ' ') - line = re.sub ('[()]', '', line.strip()).split() - # get amino-acid - sites [typ].setdefault ('aa', []).append (line[1]) - # get site class probability - probs = [] - for i in xrange (k): - probs.append (float (line[2+i])) - sites [typ].setdefault ('p'+str(i), []).append (float (line[2+i])) - sites [typ].setdefault ('pv', []).append (max (probs)) - # get most likely site class - sites [typ].setdefault ('class', []).append (int (line [3 + i])) - # if there, get omega and error - try: - sites [typ].setdefault ('w' , []).append (float (line [4 + i])) - except IndexError: - del (sites [typ]['w']) - try: - sites [typ].setdefault ('se', []).append (float (line [5 + i])) - except IndexError: - del (sites [typ]['se']) - - return {'classes': classes, - 'sites' :sites} - - -def divide_data (pamout, model): - ''' - for multiple dataset, divide outfile. - ''' - for num in range (1, int (model.properties['params']['ndata'])): - model.name = model.name + '_' + str(num) - out = open (pamout + '_' + str(num), 'w') - copy = False - for line in open (pamout): - if copy == False and \ - line.startswith('Data set '+ str (num) + '\n'): - copy = True - continue - if copy == True and \ - line.startswith('Data set '+ str (num+1) + '\n'): - break - if copy == True: - out.write(line) - out.close() - if copy == False: - warn ('WARNING: seems that you have no multiple dataset here...'\ - + '\n trying as with only one dataset') - if model.typ == 'site': - rst = '/'.join (pamout.split('/')[:-1])+'/rst' - rstout = open (rst + '_' + str(num), 'w') - copy = False - for line in open(rst): - if copy == False and \ - re.match('\t' + str (num)+'\n', line) != None: - copy = True - continue - if copy == True and \ - re.match('\t' + str (num + 1)+'\n', line) != None: - copy = False - if copy == True: - rstout.write(line) - rstout.close() - setattr (model, 'data_' + str (num), - parse_paml (pamout + '_' + str(num), model)) - else: - setattr (model, 'data_' + str (num), - parse_paml (pamout + '_' + str(num), model)) - - -def get_ancestor (pamout, model): - ''' - only for fb_ancestor model, retrieves ancestral sequences also - from rst file. - ''' - for line in open ('/'.join (pamout.split('/')[:-1])+'/rst'): - if line.startswith ('node #'): - pamlid, seq = re.sub ('node#([0-9]+)([A-Z]*)\n', '\\1\t\\2', - re.sub (' ', '', line)).split ('\t') - n = model._tree.get_descendant_by_node_id (int (pamlid)) - n.add_feature ('nt_sequence', seq) - elif line.startswith ('Node #'): - pamlid, seq = re.sub ('Node#([0-9]+)([A-Z]*)\n', '\\1\t\\2', - re.sub (' ', '', line)).split ('\t') - n = model._tree.get_descendant_by_node_id (int (pamlid)) - n.add_feature ('sequence', seq) - elif line.startswith ('Counts of changes at sites'): - break - -def parse_paml (pamout, model): - ''' - parser function for codeml files, - with values of w,dN,dS etc... dependending of the model - tested. - ''' - # if multiple dataset in same file we divide the outfile and model.name+x - if not '*' in str (model.properties['params']['ndata']): - divide_data (pamout, model) - return - all_lines = open (pamout).readlines() - # if we do not have tree, load it - if model._tree == None: - from ete2.evol import EvolTree - model._tree = EvolTree (re.findall ('\(.*\);', ''.join(all_lines))[2]) - model._tree._label_as_paml() - # starts parsing - for i, line in enumerate (all_lines): - if line is '\n': - continue - # codon frequency - if line.startswith('Codon frequencies under model'): - model.stats ['codonFreq'] = [] - for j in xrange (16): - line = map (float, re.findall ('\d\.\d+', all_lines [i+j+1])) - model.stats ['codonFreq'] += [line] - continue - if not model.stats.has_key ('codonFreq'): - continue - ###################### - # start serious staff - line = line.rstrip() - # lnL and number of parameters - if line.startswith ('lnL'): - try: - line = re.sub ('.* np: *(\d+)\): +(-\d+\.\d+).*', - '\\1 \\2', line) - model.stats ['np' ] = int (line.split()[0]) - model.stats ['lnL'] = float (line.split()[1]) - except ValueError: - line = re.sub ('.* np: *(\d+)\): +(nan).*', - '\\1 \\2', line) - model.stats ['np' ] = int (line.split()[0]) - model.stats ['lnL'] = float ('-inf') - continue - # get labels of internal branches - if line.count('..') >= 2: - labels = re.findall ('\d+\.\.\d+', line + ' ') - _check_paml_labels (model._tree, labels, pamout, model) - continue - # retrieve kappa - if line.startswith ('kappa '): - try: - model.stats ['kappa'] = float (re.sub ('.*(\d+\.\d+).*', - '\\1', line)) - except ValueError: - model.stats ['kappa'] = 'nan' - # retrieve dS dN t w N S and if present, errors. from summary table - if line.count('..') == 1 and line.startswith (' '): - if not re.match (' +\d+\.\.\d+ +\d+\.\d+ ', line): - if re.match (' +( +\d+\.\d+){8}', all_lines [i+1]): - _get_values (model, line.split ()[0]+' '+all_lines [i+1]) - continue - _get_values (model, line) - continue - -def _get_values(model, line): - ''' - just to ligther main parser - ''' - vals = line.split() - # store values under paml_id - paml_id = int (vals[0].split('..')[1]) - model.branches[paml_id].update({ - 'bL' : float (vals [1]), - 'N' : float (vals [2]), - 'S' : float (vals [3]), - 'w' : float (vals [4]), - 'dN' : float (vals [5]), - 'dS' : float (vals [6]), - 'SEdN': float (vals[vals.index ('dN') + 4]) if 'dN' in line else None, - 'SEdS': float (vals[vals.index ('dS') + 4]) if 'dS' in line else None - }) - -def _check_paml_labels (tree, paml_labels, pamout, model): - ''' - * check paml labels - Should not be necessary if all codeml is run through ETE. - ''' - try: - relations = sorted (map (lambda x: map( int, x.split('..')), - paml_labels), - key=lambda x: x[1]) - except IndexError: - return - # check that labelling corresponds with paml... - for rel in relations: - try: - node = tree.get_descendant_by_node_id(rel[1]) - if int (node.up.node_id) != int (rel[0]): - warn ('WARNING: labelling does not correspond!!\n' + \ - ' Getting them from ' + pamout) - _get_labels_from_paml(tree, relations, pamout, model) - break - except IndexError: - # if unable to find one node, relabel the whole tree - print rel - warn ('ERROR: labelling does not correspond!!\n' + \ - ' Getting them from ' + pamout) - _get_labels_from_paml(tree, relations, pamout, model) - -def _get_labels_from_paml (tree, relations, pamout, model): - ''' - in case problem in labelling... and of course it is not my fault... - retrieve node_ids from outfile... from relations line. - This may occur when loading a model that was run outside ETE. - ''' - from copy import copy - old2new = {} - # label leaves - for line in open (pamout, 'r').readlines(): - if re.search ('^#[0-9][0-9]*:', line): - nam, paml_id = re.sub ('#([0-9]+): (.*)', '\\2 \\1', - line.strip()).split() - node = (tree & nam) - old2new[node.node_id] = int(paml_id) - node.add_feature ('node_id', int(paml_id)) - if line.startswith ('Sums of codon'): - break - # label the root - tree.add_feature ('node_id', int (len (tree) + 1)) - # label other internal nodes - for node in tree.traverse(strategy='postorder'): - if node.is_root(): continue - paml_id = filter (lambda x: x[1]==node.node_id, relations)[0][0] - old2new[node.up.node_id] = paml_id - node.up.node_id = paml_id - ### change keys in branches dict of model - branches = copy(model.branches) - for b in model.branches: - model.branches[b] = branches[old2new[b]] - - - diff --git a/ete2/evol/parser/codemlparser.pyc b/ete2/evol/parser/codemlparser.pyc deleted file mode 100644 index 38dfb1d..0000000 Binary files a/ete2/evol/parser/codemlparser.pyc and /dev/null differ diff --git a/ete2/evol/parser/slrparser.py b/ete2/evol/parser/slrparser.py deleted file mode 100644 index ed6ffaa..0000000 --- a/ete2/evol/parser/slrparser.py +++ /dev/null @@ -1,94 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#!/usr/bin/python -""" -06 Feb 2011 - -parser for slr outfile -""" - -__author__ = "Francois-Jose Serra" -__email__ = "francois@barrabin.org" -__licence__ = "GPLv3" -__version__ = "0.0" - -from re import match - -def parse_slr (slrout): - SLR = {'pv':[],'w':[],'se':[], 'class':[],'note':[]} - i = 0 - w = '' - apv = '' - seP = '' - seN = '' - res = '' - note= '' - for line in open (slrout): - if line.startswith('#'): - w = line.strip().split().index('Omega')-1 - apv = line.strip().split().index('Adj.Pval')-1 - res = line.strip().split().index('Result')-1 - note= line.strip().split().index('Note')-1 - try: - seP = line.strip().split().index('upper')-1 - seN = line.strip().split().index('lower')-1 - except: - continue - continue - SLR['pv' ].append(1-float (line.split()[apv])) - SLR['w' ].append(line.split()[w]) - corr = 0 - try: - if not match('[-+]',line.split()[res]) == None: - SLR['class' ].append (5 - line.split()[res].count ('-') + line.split()[res].count ('+')) - else: - SLR['class' ].append(5) - corr = 1 - except IndexError: - SLR['class' ].append(5) - try: - SLR['note' ].append(line.split()[note-corr]) - except IndexError: - SLR['note' ].append('') - if not seN == '': - SLR['se'].append ([float (SLR['w'][-1]) - float (line.split()[seN]), - float (line.split()[seP]) - float (SLR['w'][-1])]) - return {'sites': {'SLR': SLR}} diff --git a/ete2/evol/parser/slrparser.pyc b/ete2/evol/parser/slrparser.pyc deleted file mode 100644 index 8aa0c54..0000000 Binary files a/ete2/evol/parser/slrparser.pyc and /dev/null differ diff --git a/ete2/evol/utils.py b/ete2/evol/utils.py deleted file mode 100644 index a64707f..0000000 --- a/ete2/evol/utils.py +++ /dev/null @@ -1,464 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#!/usr/bin/python -# Author: Francois-Jose Serra -# Creation Date: 2010/04/22 16:05:46 - - -# from __future__ import division # unnecessary? -from ete2 import Tree -from math import log, exp - -def get_rooting(tol, seed_species, agename = False): - ''' - returns dict of species age for a given TOL and a given seed - - **Example:** - - :: - - tol = "((((((((Drosophila melanogaster,(Drosophila simulans,Drosophila secchellia)),(Drosophila yakuba,Drosophila erecta))[&&NHX:name=melanogaster subgroup],Drosophila ananassae)[&&NHX:name=melanogaster group],(Drosophila pseudoobscura,Drosophila persimilis)[&&NHX:name=obscura group])[&&NHX:name=Sophophora Old World],Drosophila willistoni)[&&NHX:name=subgenus Sophophora],(Drosophila grimshawi,(Drosophila virilis,Drosophila mojavensis))[&&NHX:name=subgenus Drosophila])[&&NHX:name=genus Drosophila],(Anopheles gambiae,Aedes aegypti)[&&NHX:name=Culicidae])[&&NHX:name=Arthropoda],Caenorhabditis elegans)[&&NHX:name=Animalia];" - seed = "Drosophila melanogaster" - ROOTING, age2name = get_rooting (tol, seed, True) - - ROOTING == {"Aedes aegypti" : 7, - "Anopheles gambiae" : 7, - "Caenorhabditis elegans" : 8, - "Drosophila ananassae" : 3, - "Drosophila erecta" : 2, - "Drosophila grimshawi" : 6, - "Drosophila melanogaster" : 1, - "Drosophila mojavensis" : 6, - "Drosophila persimilis" : 4, - "Drosophila pseudoobscura": 4, - "Drosophila secchellia" : 1, - "Drosophila simulans" : 1, - "Drosophila virilis" : 6, - "Drosophila willistoni" : 5, - "Drosophila yakuba" : 2} - - age2name == {1: "Drosophila melanogaster. Drosophila simulans. Drosophila secchellia", - 2: "melanogaster subgroup", - 3: "melanogaster group", - 4: "Sophophora Old World", - 5: "subgenus Sophophora", - 6: "genus Drosophila", - 7: "Arthropoda", - 8: "Animalia"} - - :argument seed_species: species name - :argument False agename: if True, also returns the inverse dictionary - - :returns: ROOTING dictionary with age of each species - - ''' - - tol = Tree (tol) - try: - node = tol.search_nodes (name=seed_species)[0] - except IndexError: - exit ('ERROR: Seed species not found in tree\n') - age = 1 - ROOTING = {} - if agename: - age2name = {} - while not node.is_root(): - node = node.up - for leaf in node.get_leaf_names(): - if agename: - if node.name == 'NoName': - nam = '.'.join (node.get_leaf_names()) - else: - nam = node.name - age2name.setdefault (age, nam) - ROOTING.setdefault (leaf, age) - age += 1 - if agename: - return ROOTING, age2name - return ROOTING - - -def translate(sequence): - ''' - little function to translate DNA to protein... - from: http://python.genedrift.org/ - TODO : inseqgroup functions? - - :argument sequence: string - - :returns: translated sequence - ''' - #dictionary with the genetic code - gencode = { - 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', - 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', - 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', - 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R', - 'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', - 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P', - 'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', - 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R', - 'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', - 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A', - 'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', - 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G', - 'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', - 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L', - 'TAC':'Y', 'TAT':'Y', 'TAA':'.', 'TAG':'.', - 'TGC':'C', 'TGT':'C', 'TGA':'.', 'TGG':'W', - '---':'-', 'nnn':'x', 'NNN':'X' - } - ambig = {'Y':['A', 'G'], 'R':['C', 'T'], 'M':['G', 'T'], 'K':['A', 'C'], \ - 'S':['G', 'C'],'W':['A', 'T'], 'V':['C', 'G', 'T'], \ - 'H':['A', 'G', 'T'], 'D':['A', 'C', 'T'], 'B':['A', 'C', 'G'], \ - 'N':['A', 'C', 'G', 'T']} - proteinseq = '' - #loop to read DNA sequence in codons, 3 nucleotides at a time - sequence = sequence.upper() - for n in range(0, len(sequence), 3): - #checking to see if the dictionary has the key - try: - proteinseq += gencode[sequence[n:n+3]] - except KeyError: - newcod = [] - for nt in sequence[n:n+3]: - if ambig.has_key(nt): - newcod.append(ambig[nt]) - else : - newcod.append(list (nt)) - aa = '' - for nt1 in newcod[0]: - for nt2 in newcod[1]: - for nt3 in newcod[2]: - try: - if aa == '': - aa = gencode[nt1+nt2+nt3] - elif gencode[nt1+nt2+nt3] != aa: - aa = 'X' - break - except KeyError: - aa = 'X' - break - proteinseq += aa - return proteinseq - - -# reused from pycogent -ROUND_ERROR = 1e-14 -MAXLOG = 7.09782712893383996843E2 -big = 4.503599627370496e15 -biginv = 2.22044604925031308085e-16 -MACHEP = 1.11022302462515654042E-16 - -def chi_high(x, df): - """Returns right-hand tail of chi-square distribution (x to infinity). - - df, the degrees of freedom, ranges from 1 to infinity (assume integers). - Typically, df is (r-1)*(c-1) for a r by c table. - - Result ranges from 0 to 1. - - See Cephes docs for details. - """ - x = fix_rounding_error(x) - - if x < 0: - raise ValueError, "chi_high: x must be >= 0 (got %s)." % x - if df < 1: - raise ValueError, "chi_high: df must be >= 1 (got %s)." % df - return igamc(df/2, x/2) - -def fix_rounding_error(x): - """If x is almost in the range 0-1, fixes it. - - Specifically, if x is between -ROUND_ERROR and 0, returns 0. - If x is between 1 and 1+ROUND_ERROR, returns 1. - """ - if -ROUND_ERROR < x < 0: - return 0 - elif 1 < x < 1+ROUND_ERROR: - return 1 - else: - return x - -def igamc(a,x): - """Complemented incomplete Gamma integral: see Cephes docs.""" - if x <= 0 or a <= 0: - return 1 - if x < 1 or x < a: - return 1 - igam(a, x) - ax = a * log(x) - x - lgam(a) - if ax < -MAXLOG: #underflow - return 0 - ax = exp(ax) - #continued fraction - y = 1 - a - z = x + y + 1 - c = 0 - pkm2 = 1 - qkm2 = x - pkm1 = x + 1 - qkm1 = z * x - ans = pkm1/qkm1 - - while 1: - c += 1 - y += 1 - z += 2 - yc = y * c - pk = pkm1 * z - pkm2 * yc - qk = qkm1 * z - qkm2 * yc - if qk != 0: - r = pk/qk - t = abs((ans-r)/r) - ans = r - else: - t = 1 - pkm2 = pkm1 - pkm1 = pk - qkm2 = qkm1 - qkm1 = qk - if abs(pk) > big: - pkm2 *= biginv - pkm1 *= biginv - qkm2 *= biginv - qkm1 *= biginv - if t <= MACHEP: - break - return ans * ax - -def lgam(x): - """Natural log of the gamma fuction: see Cephes docs for details""" - sgngam = 1 - if x < -34: - q = -x - w = lgam(q) - p = floor(q) - if p == q: - raise OverflowError, "lgam returned infinity." - i = p - if i & 1 == 0: - sgngam = -1 - else: - sgngam = 1 - z = q - p - if z > 0.5: - p += 1 - z = p - q - z = q * sin(PI * z) - if z == 0: - raise OverflowError, "lgam returned infinity." - z = LOGPI - log(z) - w - return z - if x < 13: - z = 1 - p = 0 - u = x - while u >= 3: - p -= 1 - u = x + p - z *= u - while u < 2: - if u == 0: - raise OverflowError, "lgam returned infinity." - z /= u - p += 1 - u = x + p - if z < 0: - sgngam = -1 - z = -z - else: - sgngam = 1 - if u == 2: - return log(z) - p -= 2 - x = x + p - p = x * polevl(x, GB)/polevl(x,GC) - return log(z) + p - if x > MAXLGM: - raise OverflowError, "Too large a value of x in lgam." - q = (x - 0.5) * log(x) - x + LS2PI - if x > 1.0e8: - return q - p = 1/(x*x) - if x >= 1000: - q += (( 7.9365079365079365079365e-4 * p - -2.7777777777777777777778e-3) *p - + 0.0833333333333333333333) / x - else: - q += polevl(p, GA)/x - return q - -def polevl(x, coef): - """evaluates a polynomial y = C_0 + C_1x + C_2x^2 + ... + C_Nx^N - - Coefficients are stored in reverse order, i.e. coef[0] = C_N - """ - result = 0 - for c in coef: - result = result * x + c - return result - - - -def igamc(a,x): - """Complemented incomplete Gamma integral: see Cephes docs.""" - if x <= 0 or a <= 0: - return 1 - if x < 1 or x < a: - return 1 - igam(a, x) - ax = a * log(x) - x - lgam(a) - if ax < -MAXLOG: #underflow - return 0 - ax = exp(ax) - #continued fraction - y = 1 - a - z = x + y + 1 - c = 0 - pkm2 = 1 - qkm2 = x - pkm1 = x + 1 - qkm1 = z * x - ans = pkm1/qkm1 - - while 1: - c += 1 - y += 1 - z += 2 - yc = y * c - pk = pkm1 * z - pkm2 * yc - qk = qkm1 * z - qkm2 * yc - if qk != 0: - r = pk/qk - t = abs((ans-r)/r) - ans = r - else: - t = 1 - pkm2 = pkm1 - pkm1 = pk - qkm2 = qkm1 - qkm1 = qk - if abs(pk) > big: - pkm2 *= biginv - pkm1 *= biginv - qkm2 *= biginv - qkm1 *= biginv - if t <= MACHEP: - break - return ans * ax - -def igam(a, x): - """Left tail of incomplete gamma function: see Cephes docs for details""" - if x <= 0 or a <= 0: - return 0 - if x > 1 and x > a: - return 1 - igamc(a,x) - - #Compute x**a * exp(x) / Gamma(a) - - ax = a * log(x) - x - lgam(a) - if ax < -MAXLOG: #underflow - return 0.0 - ax = exp(ax) - - #power series - r = a - c = 1 - ans = 1 - while 1: - r += 1 - c *= x/r - ans += c - if c/ans <= MACHEP: - break - - return ans * ax / a - -#Coefficients for Gamma follow: -GA = [ - 8.11614167470508450300E-4, - -5.95061904284301438324E-4, - 7.93650340457716943945E-4, - -2.77777777730099687205E-3, - 8.33333333333331927722E-2, - ] - -GB = [ - -1.37825152569120859100E3, - -3.88016315134637840924E4, - -3.31612992738871184744E5, - -1.16237097492762307383E6, - -1.72173700820839662146E6, - -8.53555664245765465627E5, - ] - -GC = [ - 1.00000000000000000000E0, - -3.51815701436523470549E2, - -1.70642106651881159223E4, - -2.20528590553854454839E5, - -1.13933444367982507207E6, - -2.53252307177582951285E6, - -2.01889141433532773231E6, - ] - -GP = [ - 1.60119522476751861407E-4, - 1.19135147006586384913E-3, - 1.04213797561761569935E-2, - 4.76367800457137231464E-2, - 2.07448227648435975150E-1, - 4.94214826801497100753E-1, - 9.99999999999999996796E-1, - ] - -GQ = [ - -2.31581873324120129819E-5, - 5.39605580493303397842E-4, - -4.45641913851797240494E-3, - 1.18139785222060435552E-2, - 3.58236398605498653373E-2, - -2.34591795718243348568E-1, - 7.14304917030273074085E-2, - 1.00000000000000000320E0, - ] - -biginv = 2.22044604925031308085e-16 diff --git a/ete2/evol/utils.pyc b/ete2/evol/utils.pyc deleted file mode 100644 index acccc56..0000000 Binary files a/ete2/evol/utils.pyc and /dev/null differ diff --git a/ete2/nexml/__init__.py b/ete2/nexml/__init__.py deleted file mode 100644 index 0a141e4..0000000 --- a/ete2/nexml/__init__.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -from sys import stdout -import _nexml -from _nexml import * -from _nexml_tree import NexmlTree - -#_nexml.AbstractTree.subclass = NexmlTree -_nexml.FloatTree.subclass = NexmlTree -_nexml.IntTree.subclass = NexmlTree - -class Nexml(_nexml.Nexml): - """ Creates a new nexml project. """ - def __repr__(self): - return "NeXML project <%s>" %hex(hash(self)) - - def __init__(self, *args, **kargs): - _nexml.Nexml.__init__(self, *args, **kargs) - - def build_from_file(self, fname, index_otus=True): - """ Populate Nexml project with data in a nexml file. """ - doc = _nexml.parsexml_(fname) - rootNode = doc.getroot() - rootTag, rootClass = _nexml.get_root_tag(rootNode) - if rootClass is None: - rootTag = 'Nexml' - rootClass = self.__class__ - #rootObj = rootClass.factory() - self.build(rootNode) - - # This keeps a pointer from all trees to the parent nexml - # project. This way I can access other parts, such as otus, - # etc... - if index_otus: - id2taxa = {} - for taxa in self.get_otus(): - id2taxon = {} - for taxon in taxa.otu: - id2taxon[taxon.id] = taxon - id2taxa[taxa.id] = [taxa, id2taxon] - - for trees in self.get_trees(): - for t in trees.get_tree(): - t.set_nexml_project(self) - if trees.otus in id2taxa: - t.nexml_otus = id2taxa[trees.otus][0] - - def export(self, outfile=stdout, level=0): - namespace='xmlns:nex="http://www.nexml.org/2009"' - return super(Nexml, self).export(outfile=outfile, level=level, namespacedef_=namespace) - - -__all__ = _nexml.__all__ + ["Nexml", "NexmlTree"] diff --git a/ete2/nexml/__init__.pyc b/ete2/nexml/__init__.pyc deleted file mode 100644 index ea44812..0000000 Binary files a/ete2/nexml/__init__.pyc and /dev/null differ diff --git a/ete2/nexml/_nexml.py b/ete2/nexml/_nexml.py deleted file mode 100644 index 2b216db..0000000 --- a/ete2/nexml/_nexml.py +++ /dev/null @@ -1,16155 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Mon Jun 27 10:13:44 2011 by generateDS.py version 2.5b. -# - -import sys -import getopt -import re as re_ - -etree_ = None -Verbose_import_ = False -( XMLParser_import_none, XMLParser_import_lxml, - XMLParser_import_elementtree - ) = range(3) -XMLParser_import_library = None -try: - # lxml - from lxml import etree as etree_ - XMLParser_import_library = XMLParser_import_lxml - if Verbose_import_: - print("running with lxml.etree") -except ImportError: - try: - # cElementTree from Python 2.5+ - import xml.etree.cElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with cElementTree on Python 2.5+") - except ImportError: - try: - # ElementTree from Python 2.5+ - import xml.etree.ElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with ElementTree on Python 2.5+") - except ImportError: - try: - # normal cElementTree install - import cElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with cElementTree") - except ImportError: - try: - # normal ElementTree install - import elementtree.ElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with ElementTree") - except ImportError: - raise ImportError("Failed to import ElementTree from any known place") - -def parsexml_(*args, **kwargs): - if (XMLParser_import_library == XMLParser_import_lxml and - 'parser' not in kwargs): - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - kwargs['parser'] = etree_.ETCompatXMLParser() - doc = etree_.parse(*args, **kwargs) - return doc - -# -# User methods -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ImportError, exp: - - class GeneratedsSuper(object): - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_validate_string(self, input_data, node, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % input_data - def gds_validate_integer(self, input_data, node, input_name=''): - return input_data - def gds_format_integer_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_integer_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - try: - fvalue = float(value) - except (TypeError, ValueError), exp: - raise_parse_error(node, 'Requires sequence of integers') - return input_data - def gds_format_float(self, input_data, input_name=''): - return '%f' % input_data - def gds_validate_float(self, input_data, node, input_name=''): - return input_data - def gds_format_float_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_float_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - try: - fvalue = float(value) - except (TypeError, ValueError), exp: - raise_parse_error(node, 'Requires sequence of floats') - return input_data - def gds_format_double(self, input_data, input_name=''): - return '%e' % input_data - def gds_validate_double(self, input_data, node, input_name=''): - return input_data - def gds_format_double_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_double_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - try: - fvalue = float(value) - except (TypeError, ValueError), exp: - raise_parse_error(node, 'Requires sequence of doubles') - return input_data - def gds_format_boolean(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_boolean(self, input_data, node, input_name=''): - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_boolean_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - if value not in ('true', '1', 'false', '0', ): - raise_parse_error(node, 'Requires sequence of booleans ("true", "1", "false", "0")') - return input_data - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = 'utf-8' -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -STRING_CLEANUP_PAT = re_.compile(r"[\n\r\s]+") - -# -# Support/utility functions. -# - -def showIndent(outfile, level): - for idx in range(level): - outfile.write(' ') - -def quote_xml(inStr): - if not inStr: - return '' - s1 = (isinstance(inStr, basestring) and inStr or - '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - -def quote_attrib(inStr): - s1 = (isinstance(inStr, basestring) and inStr or - '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - -def find_attr_value_(attr_name, node): - attrs = node.attrib - # First try with no namespace. - value = attrs.get(attr_name) - if value is None: - # Now try the other possible namespaces. - namespaces = node.nsmap.itervalues() - for namespace in namespaces: - value = attrs.get('{%s}%s' % (namespace, attr_name, )) - if value is not None: - break - return value - - -class GDSParseError(Exception): - pass - -def raise_parse_error(node, msg): - if XMLParser_import_library == XMLParser_import_lxml: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - else: - msg = '%s (element %s)' % (msg, node.tag, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export(outfile, level, namespace,name) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % (self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % (self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % (self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % (self.name, self.value, self.name)) - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % \ - (self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0): - self.name = name - self.data_type = data_type - self.container = container - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - -class Base(GeneratedsSuper): - """The base type for all complexType definitions in the nexml schema. - This type allows a number of special attributes: xml:lang - for - languages codes xml:base - see http://www.w3.org/TR/xmlbase/ - xml:id - see http://www.w3.org/TR/xml-id/ xml:space - for - whitespace handling xlink:href - for links Also see - http://www.w3.org/2001/xml.xsd for more information on the xml - and xlink attributes.""" - subclass = None - superclass = None - def __init__(self, valueOf_=None): - self.anyAttributes_ = {} - def factory(*args_, **kwargs_): - if Base.subclass: - return Base.subclass(*args_, **kwargs_) - else: - return Base(*args_, **kwargs_) - factory = staticmethod(factory) - def get_anyAttributes_(self): return self.anyAttributes_ - def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_ - def export(self, outfile, level, namespace_='', name_='Base', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Base') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='Base'): - for name, value in self.anyAttributes_.items(): - xsinamespaceprefix = 'xsi' - xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance' - xsinamespace2 = '{%s}' % (xsinamespace1, ) - if name.startswith(xsinamespace2): - name1 = name[len(xsinamespace2):] - name2 = '%s:%s' % (xsinamespaceprefix, name1, ) - if name2 not in already_processed: - already_processed.append(name2) - outfile.write(' %s=%s' % (name2, quote_attrib(value), )) - else: - if name not in already_processed: - already_processed.append(name) - outfile.write(' %s=%s' % (name, quote_attrib(value), )) - pass - def exportChildren(self, outfile, level, namespace_='', name_='Base', fromsubclass_=False): - pass - def hasContent_(self): - if ( - - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Base'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - for name, value in self.anyAttributes_.items(): - showIndent(outfile, level) - outfile.write('%s = "%s",\n' % (name, value,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - self.anyAttributes_ = {} - for name, value in attrs.items(): - if name not in already_processed: - self.anyAttributes_[name] = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class Base - - -class Meta(Base): - subclass = None - superclass = Base - def __init__(self, valueOf_=None): - super(Meta, self).__init__() - pass - def factory(*args_, **kwargs_): - if Meta.subclass: - return Meta.subclass(*args_, **kwargs_) - else: - return Meta(*args_, **kwargs_) - factory = staticmethod(factory) - def export(self, outfile, level, namespace_='', name_='Meta', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Meta') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="Meta"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='Meta'): - super(Meta, self).exportAttributes(outfile, level, already_processed, namespace_, name_='Meta') - def exportChildren(self, outfile, level, namespace_='', name_='Meta', fromsubclass_=False): - super(Meta, self).exportChildren(outfile, level, namespace_, name_, True) - pass - def hasContent_(self): - if ( - super(Meta, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Meta'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(Meta, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(Meta, self).exportLiteralChildren(outfile, level, name_) - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(Meta, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(Meta, self).buildChildren(child_, node, nodeName_, True) - pass -# end class Meta - - -class ResourceMeta(Meta): - """Metadata annotations in which the object is a resource. If this - element contains meta elements as children, then the object of - this annotation is a "blank node".""" - subclass = None - superclass = Meta - def __init__(self, href=None, rel=None, meta=None, valueOf_=None): - super(ResourceMeta, self).__init__() - self.href = _cast(None, href) - self.rel = _cast(None, rel) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if ResourceMeta.subclass: - return ResourceMeta.subclass(*args_, **kwargs_) - else: - return ResourceMeta(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_href(self): return self.href - def set_href(self, href): self.href = href - def get_rel(self): return self.rel - def set_rel(self, rel): self.rel = rel - def export(self, outfile, level, namespace_='', name_='ResourceMeta', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ResourceMeta') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="ResourceMeta"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ResourceMeta'): - super(ResourceMeta, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ResourceMeta') - if self.href is not None and 'href' not in already_processed: - already_processed.append('href') - outfile.write(' href=%s' % (quote_attrib(self.href), )) - if self.rel is not None and 'rel' not in already_processed: - already_processed.append('rel') - outfile.write(' rel=%s' % (quote_attrib(self.rel), )) - def exportChildren(self, outfile, level, namespace_='', name_='ResourceMeta', fromsubclass_=False): - super(ResourceMeta, self).exportChildren(outfile, level, namespace_, name_, True) - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(ResourceMeta, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ResourceMeta'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.href is not None and 'href' not in already_processed: - already_processed.append('href') - showIndent(outfile, level) - outfile.write('href = %s,\n' % (self.href,)) - if self.rel is not None and 'rel' not in already_processed: - already_processed.append('rel') - showIndent(outfile, level) - outfile.write('rel = %s,\n' % (self.rel,)) - super(ResourceMeta, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ResourceMeta, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('href', node) - if value is not None and 'href' not in already_processed: - already_processed.append('href') - self.href = value - value = find_attr_value_('rel', node) - if value is not None and 'rel' not in already_processed: - already_processed.append('rel') - self.rel = value - super(ResourceMeta, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - super(ResourceMeta, self).buildChildren(child_, node, nodeName_, True) -# end class ResourceMeta - - -class LiteralMeta(Meta): - """Metadata annotations in which the object is a literal value. If the - @content attribute is used, then the element should contain no - children.""" - subclass = None - superclass = Meta - def __init__(self, datatype=None, content=None, property=None, valueOf_=None): - super(LiteralMeta, self).__init__() - self.datatype = _cast(None, datatype) - self.content = _cast(None, content) - self.property = _cast(None, property) - pass - def factory(*args_, **kwargs_): - if LiteralMeta.subclass: - return LiteralMeta.subclass(*args_, **kwargs_) - else: - return LiteralMeta(*args_, **kwargs_) - factory = staticmethod(factory) - def get_datatype(self): return self.datatype - def set_datatype(self, datatype): self.datatype = datatype - def get_content(self): return self.content - def set_content(self, content): self.content = content - def get_property(self): return self.property - def set_property(self, property): self.property = property - def export(self, outfile, level, namespace_='', name_='LiteralMeta', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='LiteralMeta') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="LiteralMeta"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='LiteralMeta'): - super(LiteralMeta, self).exportAttributes(outfile, level, already_processed, namespace_, name_='LiteralMeta') - if self.datatype is not None and 'datatype' not in already_processed: - already_processed.append('datatype') - outfile.write(' datatype=%s' % (quote_attrib(self.datatype), )) - if self.content is not None and 'content' not in already_processed: - already_processed.append('content') - outfile.write(' content=%s' % (self.gds_format_string(quote_attrib(self.content).encode(ExternalEncoding), input_name='content'), )) - if self.property is not None and 'property' not in already_processed: - already_processed.append('property') - outfile.write(' property=%s' % (quote_attrib(self.property), )) - def exportChildren(self, outfile, level, namespace_='', name_='LiteralMeta', fromsubclass_=False): - super(LiteralMeta, self).exportChildren(outfile, level, namespace_, name_, True) - pass - def hasContent_(self): - if ( - super(LiteralMeta, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='LiteralMeta'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.datatype is not None and 'datatype' not in already_processed: - already_processed.append('datatype') - showIndent(outfile, level) - outfile.write('datatype = %s,\n' % (self.datatype,)) - if self.content is not None and 'content' not in already_processed: - already_processed.append('content') - showIndent(outfile, level) - outfile.write('content = "%s",\n' % (self.content,)) - if self.property is not None and 'property' not in already_processed: - already_processed.append('property') - showIndent(outfile, level) - outfile.write('property = %s,\n' % (self.property,)) - super(LiteralMeta, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(LiteralMeta, self).exportLiteralChildren(outfile, level, name_) - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('datatype', node) - if value is not None and 'datatype' not in already_processed: - already_processed.append('datatype') - self.datatype = value - value = find_attr_value_('content', node) - if value is not None and 'content' not in already_processed: - already_processed.append('content') - self.content = value - value = find_attr_value_('property', node) - if value is not None and 'property' not in already_processed: - already_processed.append('property') - self.property = value - super(LiteralMeta, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(LiteralMeta, self).buildChildren(child_, node, nodeName_, True) - pass -# end class LiteralMeta - - -class attrExtensions(GeneratedsSuper): - """This element is for use in WSDL 1.1 only. It does not apply to WSDL - 2.0 documents. Use in WSDL 2.0 documents is invalid.""" - subclass = None - superclass = None - def __init__(self, valueOf_=None): - self.anyAttributes_ = {} - def factory(*args_, **kwargs_): - if attrExtensions.subclass: - return attrExtensions.subclass(*args_, **kwargs_) - else: - return attrExtensions(*args_, **kwargs_) - factory = staticmethod(factory) - def get_anyAttributes_(self): return self.anyAttributes_ - def set_anyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_ - def export(self, outfile, level, namespace_='', name_='attrExtensions', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='attrExtensions') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='attrExtensions'): - for name, value in self.anyAttributes_.items(): - xsinamespaceprefix = 'xsi' - xsinamespace1 = 'http://www.w3.org/2001/XMLSchema-instance' - xsinamespace2 = '{%s}' % (xsinamespace1, ) - if name.startswith(xsinamespace2): - name1 = name[len(xsinamespace2):] - name2 = '%s:%s' % (xsinamespaceprefix, name1, ) - if name2 not in already_processed: - already_processed.append(name2) - outfile.write(' %s=%s' % (name2, quote_attrib(value), )) - else: - if name not in already_processed: - already_processed.append(name) - outfile.write(' %s=%s' % (name, quote_attrib(value), )) - pass - def exportChildren(self, outfile, level, namespace_='', name_='attrExtensions', fromsubclass_=False): - pass - def hasContent_(self): - if ( - - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='attrExtensions'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - for name, value in self.anyAttributes_.items(): - showIndent(outfile, level) - outfile.write('%s = "%s",\n' % (name, value,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - self.anyAttributes_ = {} - for name, value in attrs.items(): - if name not in already_processed: - self.anyAttributes_[name] = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class attrExtensions - - -class AbstractMapping(Base): - """The AbstractMapping type is the superclass for an ambiguity mapping. - In an instance document, a subclass of this type will look like - , i.e. an element called "member" with an - attribute called "state" whose value is an id reference that - refers to an element that subclasses AbstractState. The purpose - of AbstractMapping is to specify which other states may be - implied, e.g. a nucleotide symbol "N" would have mappings to - "A", "C", "G" and "T".""" - subclass = None - superclass = Base - def __init__(self, state=None, valueOf_=None): - super(AbstractMapping, self).__init__() - self.state = _cast(None, state) - pass - def factory(*args_, **kwargs_): - if AbstractMapping.subclass: - return AbstractMapping.subclass(*args_, **kwargs_) - else: - return AbstractMapping(*args_, **kwargs_) - factory = staticmethod(factory) - def get_state(self): return self.state - def set_state(self, state): self.state = state - def export(self, outfile, level, namespace_='', name_='AbstractMapping', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractMapping') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractMapping"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractMapping'): - super(AbstractMapping, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractMapping') - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - outfile.write(' state=%s' % (self.gds_format_string(quote_attrib(self.state).encode(ExternalEncoding), input_name='state'), )) - def exportChildren(self, outfile, level, namespace_='', name_='AbstractMapping', fromsubclass_=False): - super(AbstractMapping, self).exportChildren(outfile, level, namespace_, name_, True) - pass - def hasContent_(self): - if ( - super(AbstractMapping, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractMapping'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - showIndent(outfile, level) - outfile.write('state = "%s",\n' % (self.state,)) - super(AbstractMapping, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractMapping, self).exportLiteralChildren(outfile, level, name_) - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('state', node) - if value is not None and 'state' not in already_processed: - already_processed.append('state') - self.state = value - super(AbstractMapping, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(AbstractMapping, self).buildChildren(child_, node, nodeName_, True) - pass -# end class AbstractMapping - - -class DNAMapping(AbstractMapping): - """An IUPAC ambiguity mapping.""" - subclass = None - superclass = AbstractMapping - def __init__(self, state=None, valueOf_=None): - super(DNAMapping, self).__init__(state, ) - pass - def factory(*args_, **kwargs_): - if DNAMapping.subclass: - return DNAMapping.subclass(*args_, **kwargs_) - else: - return DNAMapping(*args_, **kwargs_) - factory = staticmethod(factory) - def export(self, outfile, level, namespace_='', name_='DNAMapping', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNAMapping') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNAMapping'): - super(DNAMapping, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNAMapping') - def exportChildren(self, outfile, level, namespace_='', name_='DNAMapping', fromsubclass_=False): - pass - def hasContent_(self): - if ( - super(DNAMapping, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNAMapping'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(DNAMapping, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNAMapping, self).exportLiteralChildren(outfile, level, name_) - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(DNAMapping, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class DNAMapping - - -class AAMapping(AbstractMapping): - """An IUPAC ambiguity mapping.""" - subclass = None - superclass = AbstractMapping - def __init__(self, state=None, valueOf_=None): - super(AAMapping, self).__init__(state, ) - pass - def factory(*args_, **kwargs_): - if AAMapping.subclass: - return AAMapping.subclass(*args_, **kwargs_) - else: - return AAMapping(*args_, **kwargs_) - factory = staticmethod(factory) - def export(self, outfile, level, namespace_='', name_='AAMapping', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AAMapping') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AAMapping'): - super(AAMapping, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AAMapping') - def exportChildren(self, outfile, level, namespace_='', name_='AAMapping', fromsubclass_=False): - pass - def hasContent_(self): - if ( - super(AAMapping, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AAMapping'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AAMapping, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AAMapping, self).exportLiteralChildren(outfile, level, name_) - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AAMapping, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class AAMapping - - -class RNAMapping(AbstractMapping): - """An IUPAC RNA ambiguity mapping.""" - subclass = None - superclass = AbstractMapping - def __init__(self, state=None, valueOf_=None): - super(RNAMapping, self).__init__(state, ) - pass - def factory(*args_, **kwargs_): - if RNAMapping.subclass: - return RNAMapping.subclass(*args_, **kwargs_) - else: - return RNAMapping(*args_, **kwargs_) - factory = staticmethod(factory) - def export(self, outfile, level, namespace_='', name_='RNAMapping', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNAMapping') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNAMapping'): - super(RNAMapping, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNAMapping') - def exportChildren(self, outfile, level, namespace_='', name_='RNAMapping', fromsubclass_=False): - pass - def hasContent_(self): - if ( - super(RNAMapping, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNAMapping'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RNAMapping, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNAMapping, self).exportLiteralChildren(outfile, level, name_) - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RNAMapping, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class RNAMapping - - -class StandardMapping(AbstractMapping): - """A standard character ambiguity mapping.""" - subclass = None - superclass = AbstractMapping - def __init__(self, state=None, valueOf_=None): - super(StandardMapping, self).__init__(state, ) - pass - def factory(*args_, **kwargs_): - if StandardMapping.subclass: - return StandardMapping.subclass(*args_, **kwargs_) - else: - return StandardMapping(*args_, **kwargs_) - factory = staticmethod(factory) - def export(self, outfile, level, namespace_='', name_='StandardMapping', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardMapping') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardMapping'): - super(StandardMapping, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardMapping') - def exportChildren(self, outfile, level, namespace_='', name_='StandardMapping', fromsubclass_=False): - pass - def hasContent_(self): - if ( - super(StandardMapping, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardMapping'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(StandardMapping, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardMapping, self).exportLiteralChildren(outfile, level, name_) - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(StandardMapping, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class StandardMapping - - -class Annotated(Base): - """The Annotated complexType is a super class for objects that - optionally have metadata annotations of type Meta.""" - subclass = None - superclass = Base - def __init__(self, about=None, meta=None, valueOf_=None): - super(Annotated, self).__init__() - self.about = _cast(None, about) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if Annotated.subclass: - return Annotated.subclass(*args_, **kwargs_) - else: - return Annotated(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_about(self): return self.about - def set_about(self, about): self.about = about - def export(self, outfile, level, namespace_='', name_='Annotated', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Annotated') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="Annotated"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='Annotated'): - super(Annotated, self).exportAttributes(outfile, level, already_processed, namespace_, name_='Annotated') - if self.about is not None and 'about' not in already_processed: - already_processed.append('about') - outfile.write(' about=%s' % (quote_attrib(self.about), )) - def exportChildren(self, outfile, level, namespace_='', name_='Annotated', fromsubclass_=False): - super(Annotated, self).exportChildren(outfile, level, namespace_, name_, True) - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(Annotated, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Annotated'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.about is not None and 'about' not in already_processed: - already_processed.append('about') - showIndent(outfile, level) - outfile.write('about = %s,\n' % (self.about,)) - super(Annotated, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(Annotated, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('about', node) - if value is not None and 'about' not in already_processed: - already_processed.append('about') - self.about = value - super(Annotated, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - super(Annotated, self).buildChildren(child_, node, nodeName_, True) -# end class Annotated - - -class Nexml(Annotated): - """The root element for nexml.""" - subclass = None - superclass = Annotated - def __init__(self, about=None, meta=None, version=None, generator=None, otus=None, characters=None, trees=None, valueOf_=None): - super(Nexml, self).__init__(about, meta, ) - self.version = _cast(None, version) - self.generator = _cast(None, generator) - if otus is None: - self.otus = [] - else: - self.otus = otus - if characters is None: - self.characters = [] - else: - self.characters = characters - if trees is None: - self.trees = [] - else: - self.trees = trees - def factory(*args_, **kwargs_): - if Nexml.subclass: - return Nexml.subclass(*args_, **kwargs_) - else: - return Nexml(*args_, **kwargs_) - factory = staticmethod(factory) - def get_otus(self): return self.otus - def set_otus(self, otus): self.otus = otus - def add_otus(self, value): self.otus.append(value) - def insert_otus(self, index, value): self.otus[index] = value - def get_characters(self): return self.characters - def set_characters(self, characters): self.characters = characters - def add_characters(self, value): self.characters.append(value) - def insert_characters(self, index, value): self.characters[index] = value - def get_trees(self): return self.trees - def set_trees(self, trees): self.trees = trees - def add_trees(self, value): self.trees.append(value) - def insert_trees(self, index, value): self.trees[index] = value - def get_version(self): return self.version - def set_version(self, version): self.version = version - def validate_Nexml1_0(self, value): - # Validate type Nexml1_0, a restriction on xs:decimal. - pass - def get_generator(self): return self.generator - def set_generator(self, generator): self.generator = generator - def export(self, outfile, level, namespace_='', name_='Nexml', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Nexml') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="Nexml"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='Nexml'): - super(Nexml, self).exportAttributes(outfile, level, already_processed, namespace_, name_='Nexml') - if self.version is not None and 'version' not in already_processed: - already_processed.append('version') - outfile.write(' version=%s' % (quote_attrib(self.version), )) - if self.generator is not None and 'generator' not in already_processed: - already_processed.append('generator') - outfile.write(' generator=%s' % (self.gds_format_string(quote_attrib(self.generator).encode(ExternalEncoding), input_name='generator'), )) - def exportChildren(self, outfile, level, namespace_='', name_='Nexml', fromsubclass_=False): - super(Nexml, self).exportChildren(outfile, level, namespace_, name_, True) - for otus_ in self.otus: - otus_.export(outfile, level, namespace_, name_='otus') - for characters_ in self.get_characters(): - characters_.export(outfile, level, namespace_, name_='characters') - for trees_ in self.trees: - trees_.export(outfile, level, namespace_, name_='trees') - def hasContent_(self): - if ( - self.otus or - self.characters or - self.trees or - super(Nexml, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Nexml'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.version is not None and 'version' not in already_processed: - already_processed.append('version') - showIndent(outfile, level) - outfile.write('version = %f,\n' % (self.version,)) - if self.generator is not None and 'generator' not in already_processed: - already_processed.append('generator') - showIndent(outfile, level) - outfile.write('generator = "%s",\n' % (self.generator,)) - super(Nexml, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(Nexml, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('otus=[\n') - level += 1 - for otus_ in self.otus: - showIndent(outfile, level) - outfile.write('model_.Taxa(\n') - otus_.exportLiteral(outfile, level, name_='Taxa') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('characters=[\n') - level += 1 - for characters_ in self.characters: - showIndent(outfile, level) - outfile.write('model_.AbstractBlock(\n') - characters_.exportLiteral(outfile, level, name_='AbstractBlock') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('trees=[\n') - level += 1 - for trees_ in self.trees: - showIndent(outfile, level) - outfile.write('model_.Trees(\n') - trees_.exportLiteral(outfile, level, name_='Trees') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('version', node) - if value is not None and 'version' not in already_processed: - already_processed.append('version') - try: - self.version = float(value) - except ValueError, exp: - raise ValueError('Bad float/double attribute (version): %s' % exp) - self.validate_Nexml1_0(self.version) # validate type Nexml1_0 - value = find_attr_value_('generator', node) - if value is not None and 'generator' not in already_processed: - already_processed.append('generator') - self.generator = value - super(Nexml, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'otus': - obj_ = Taxa.factory() - obj_.build(child_) - self.otus.append(obj_) - elif nodeName_ == 'characters': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.characters.append(obj_) - elif nodeName_ == 'trees': - obj_ = Trees.factory() - obj_.build(child_) - self.trees.append(obj_) - super(Nexml, self).buildChildren(child_, node, nodeName_, True) -# end class Nexml - - -class AbstractObsMatrix(Annotated): - """The AbstractObsMatrix super class is the abstract type for a - element that contains rows which hold granular state - observations.""" - subclass = None - superclass = Annotated - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(AbstractObsMatrix, self).__init__(about, meta, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AbstractObsMatrix.subclass: - return AbstractObsMatrix.subclass(*args_, **kwargs_) - else: - return AbstractObsMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AbstractObsMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractObsMatrix') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractObsMatrix"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractObsMatrix'): - super(AbstractObsMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractObsMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractObsMatrix', fromsubclass_=False): - super(AbstractObsMatrix, self).exportChildren(outfile, level, namespace_, name_, True) - for row_ in self.get_row(): - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(AbstractObsMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractObsMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractObsMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractObsMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.AbstractObsRow(\n') - row_.exportLiteral(outfile, level, name_='AbstractObsRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractObsMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) - super(AbstractObsMatrix, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractObsMatrix - - -class AbstractSeqMatrix(Annotated): - """The AbstractSeqMatrix super class is the abstract type for a - element that contains rows which hold raw character - sequences.""" - subclass = None - superclass = Annotated - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(AbstractSeqMatrix, self).__init__(about, meta, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AbstractSeqMatrix.subclass: - return AbstractSeqMatrix.subclass(*args_, **kwargs_) - else: - return AbstractSeqMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AbstractSeqMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractSeqMatrix') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractSeqMatrix"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractSeqMatrix'): - super(AbstractSeqMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractSeqMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractSeqMatrix', fromsubclass_=False): - super(AbstractSeqMatrix, self).exportChildren(outfile, level, namespace_, name_, True) - for row_ in self.get_row(): - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(AbstractSeqMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractSeqMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractSeqMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractSeqMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.AbstractSeqRow(\n') - row_.exportLiteral(outfile, level, name_='AbstractSeqRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractSeqMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) - super(AbstractSeqMatrix, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractSeqMatrix - - -class AbstractFormat(Annotated): - """The AbstractFormat type is the superclass for the element that - defines the allowed characters and states in a matrix, and their - ambiguity mapping. It may enclose AbstractStates elements that - define states and their mappings, and AbstractChar elements that - specify which AbstractStates apply to which matrix columns.""" - subclass = None - superclass = Annotated - def __init__(self, about=None, meta=None, states=None, char=None, set=None, valueOf_=None): - super(AbstractFormat, self).__init__(about, meta, ) - if states is None: - self.states = [] - else: - self.states = states - if char is None: - self.char = [] - else: - self.char = char - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AbstractFormat.subclass: - return AbstractFormat.subclass(*args_, **kwargs_) - else: - return AbstractFormat(*args_, **kwargs_) - factory = staticmethod(factory) - def get_states(self): return self.states - def set_states(self, states): self.states = states - def add_states(self, value): self.states.append(value) - def insert_states(self, index, value): self.states[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def add_char(self, value): self.char.append(value) - def insert_char(self, index, value): self.char[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AbstractFormat', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractFormat') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractFormat"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractFormat'): - super(AbstractFormat, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractFormat') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractFormat', fromsubclass_=False): - super(AbstractFormat, self).exportChildren(outfile, level, namespace_, name_, True) - for states_ in self.get_states(): - states_.export(outfile, level, namespace_, name_='states') - for char_ in self.get_char(): - char_.export(outfile, level, namespace_, name_='char') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.states or - self.char or - self.set or - super(AbstractFormat, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractFormat'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractFormat, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractFormat, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('states=[\n') - level += 1 - for states_ in self.states: - showIndent(outfile, level) - outfile.write('model_.AbstractStates(\n') - states_.exportLiteral(outfile, level, name_='AbstractStates') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('char=[\n') - level += 1 - for char_ in self.char: - showIndent(outfile, level) - outfile.write('model_.AbstractChar(\n') - char_.exportLiteral(outfile, level, name_='AbstractChar') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CharSet(\n') - set_.exportLiteral(outfile, level, name_='CharSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractFormat, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'states': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.states.append(obj_) - elif nodeName_ == 'char': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.char.append(obj_) - elif nodeName_ == 'set': - obj_ = CharSet.factory() - obj_.build(child_) - self.set.append(obj_) - super(AbstractFormat, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractFormat - - -class ContinuousObsMatrix(AbstractObsMatrix): - """A matrix of rows with single character observations.""" - subclass = None - superclass = AbstractObsMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(ContinuousObsMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if ContinuousObsMatrix.subclass: - return ContinuousObsMatrix.subclass(*args_, **kwargs_) - else: - return ContinuousObsMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='ContinuousObsMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousObsMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ContinuousObsMatrix'): - super(ContinuousObsMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousObsMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='ContinuousObsMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(ContinuousObsMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ContinuousObsMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(ContinuousObsMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ContinuousObsMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.ContinuousMatrixObsRow(\n') - row_.exportLiteral(outfile, level, name_='ContinuousMatrixObsRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(ContinuousObsMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = ContinuousMatrixObsRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class ContinuousObsMatrix - - -class ContinuousSeqMatrix(AbstractSeqMatrix): - """A matrix of rows with seq strings of type continuous.""" - subclass = None - superclass = AbstractSeqMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(ContinuousSeqMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if ContinuousSeqMatrix.subclass: - return ContinuousSeqMatrix.subclass(*args_, **kwargs_) - else: - return ContinuousSeqMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='ContinuousSeqMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousSeqMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ContinuousSeqMatrix'): - super(ContinuousSeqMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousSeqMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='ContinuousSeqMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(ContinuousSeqMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ContinuousSeqMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(ContinuousSeqMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ContinuousSeqMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.ContinuousMatrixSeqRow(\n') - row_.exportLiteral(outfile, level, name_='ContinuousMatrixSeqRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(ContinuousSeqMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = ContinuousMatrixSeqRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class ContinuousSeqMatrix - - -class ContinuousFormat(AbstractFormat): - """The ContinuousFormat class is the container of continuous column - definitions.""" - subclass = None - superclass = AbstractFormat - def __init__(self, about=None, meta=None, states=None, char=None, set=None, valueOf_=None): - super(ContinuousFormat, self).__init__(about, meta, states, char, set, ) - if char is None: - self.char = [] - else: - self.char = char - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if ContinuousFormat.subclass: - return ContinuousFormat.subclass(*args_, **kwargs_) - else: - return ContinuousFormat(*args_, **kwargs_) - factory = staticmethod(factory) - def get_char(self): return self.char - def set_char(self, char): self.char = char - def add_char(self, value): self.char.append(value) - def insert_char(self, index, value): self.char[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='ContinuousFormat', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousFormat') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ContinuousFormat'): - super(ContinuousFormat, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousFormat') - def exportChildren(self, outfile, level, namespace_='', name_='ContinuousFormat', fromsubclass_=False): - for char_ in self.char: - char_.export(outfile, level, namespace_, name_='char') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.char or - self.set or - super(ContinuousFormat, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ContinuousFormat'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(ContinuousFormat, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ContinuousFormat, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('char=[\n') - level += 1 - for char_ in self.char: - showIndent(outfile, level) - outfile.write('model_.ContinuousChar(\n') - char_.exportLiteral(outfile, level, name_='ContinuousChar') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CharSet(\n') - set_.exportLiteral(outfile, level, name_='CharSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(ContinuousFormat, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'char': - obj_ = ContinuousChar.factory() - obj_.build(child_) - self.char.append(obj_) - elif nodeName_ == 'set': - obj_ = CharSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class ContinuousFormat - - -class Labelled(Annotated): - """The Labelled complexType is a super class for objects that - optionally have label attributes to use as a (non-unique) name - of type xs:string.""" - subclass = None - superclass = Annotated - def __init__(self, about=None, meta=None, label=None, valueOf_=None): - super(Labelled, self).__init__(about, meta, ) - self.label = _cast(None, label) - pass - def factory(*args_, **kwargs_): - if Labelled.subclass: - return Labelled.subclass(*args_, **kwargs_) - else: - return Labelled(*args_, **kwargs_) - factory = staticmethod(factory) - def get_label(self): return self.label - def set_label(self, label): self.label = label - def export(self, outfile, level, namespace_='', name_='Labelled', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Labelled') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="Labelled"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='Labelled'): - super(Labelled, self).exportAttributes(outfile, level, already_processed, namespace_, name_='Labelled') - if self.label is not None and 'label' not in already_processed: - already_processed.append('label') - outfile.write(' label=%s' % (self.gds_format_string(quote_attrib(self.label).encode(ExternalEncoding), input_name='label'), )) - def exportChildren(self, outfile, level, namespace_='', name_='Labelled', fromsubclass_=False): - super(Labelled, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(Labelled, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Labelled'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.label is not None and 'label' not in already_processed: - already_processed.append('label') - showIndent(outfile, level) - outfile.write('label = "%s",\n' % (self.label,)) - super(Labelled, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(Labelled, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('label', node) - if value is not None and 'label' not in already_processed: - already_processed.append('label') - self.label = value - super(Labelled, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(Labelled, self).buildChildren(child_, node, nodeName_, True) - pass -# end class Labelled - - -class StandardObsMatrix(AbstractObsMatrix): - """A matrix of rows with single character observations.""" - subclass = None - superclass = AbstractObsMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(StandardObsMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if StandardObsMatrix.subclass: - return StandardObsMatrix.subclass(*args_, **kwargs_) - else: - return StandardObsMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='StandardObsMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardObsMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardObsMatrix'): - super(StandardObsMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardObsMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='StandardObsMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(StandardObsMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardObsMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(StandardObsMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardObsMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.StandardMatrixObsRow(\n') - row_.exportLiteral(outfile, level, name_='StandardMatrixObsRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(StandardObsMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = StandardMatrixObsRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class StandardObsMatrix - - -class StandardSeqMatrix(AbstractSeqMatrix): - """A matrix of rows with seq strings of type standard.""" - subclass = None - superclass = AbstractSeqMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(StandardSeqMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if StandardSeqMatrix.subclass: - return StandardSeqMatrix.subclass(*args_, **kwargs_) - else: - return StandardSeqMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='StandardSeqMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardSeqMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardSeqMatrix'): - super(StandardSeqMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardSeqMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='StandardSeqMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(StandardSeqMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardSeqMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(StandardSeqMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardSeqMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.StandardMatrixSeqRow(\n') - row_.exportLiteral(outfile, level, name_='StandardMatrixSeqRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(StandardSeqMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = StandardMatrixSeqRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class StandardSeqMatrix - - -class StandardFormat(AbstractFormat): - """The StandardFormat class is the container of standard column - definitions.""" - subclass = None - superclass = AbstractFormat - def __init__(self, about=None, meta=None, states=None, char=None, set=None, valueOf_=None): - super(StandardFormat, self).__init__(about, meta, states, char, set, ) - if states is None: - self.states = [] - else: - self.states = states - if char is None: - self.char = [] - else: - self.char = char - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if StandardFormat.subclass: - return StandardFormat.subclass(*args_, **kwargs_) - else: - return StandardFormat(*args_, **kwargs_) - factory = staticmethod(factory) - def get_states(self): return self.states - def set_states(self, states): self.states = states - def add_states(self, value): self.states.append(value) - def insert_states(self, index, value): self.states[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def add_char(self, value): self.char.append(value) - def insert_char(self, index, value): self.char[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='StandardFormat', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardFormat') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardFormat'): - super(StandardFormat, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardFormat') - def exportChildren(self, outfile, level, namespace_='', name_='StandardFormat', fromsubclass_=False): - for states_ in self.states: - states_.export(outfile, level, namespace_, name_='states') - for char_ in self.char: - char_.export(outfile, level, namespace_, name_='char') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.states or - self.char or - self.set or - super(StandardFormat, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardFormat'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(StandardFormat, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardFormat, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('states=[\n') - level += 1 - for states_ in self.states: - showIndent(outfile, level) - outfile.write('model_.StandardStates(\n') - states_.exportLiteral(outfile, level, name_='StandardStates') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('char=[\n') - level += 1 - for char_ in self.char: - showIndent(outfile, level) - outfile.write('model_.StandardChar(\n') - char_.exportLiteral(outfile, level, name_='StandardChar') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CharSet(\n') - set_.exportLiteral(outfile, level, name_='CharSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(StandardFormat, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'states': - obj_ = StandardStates.factory() - obj_.build(child_) - self.states.append(obj_) - elif nodeName_ == 'char': - obj_ = StandardChar.factory() - obj_.build(child_) - self.char.append(obj_) - elif nodeName_ == 'set': - obj_ = CharSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class StandardFormat - - -class RNAObsMatrix(AbstractObsMatrix): - """A matrix of rows with single character observations.""" - subclass = None - superclass = AbstractObsMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(RNAObsMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if RNAObsMatrix.subclass: - return RNAObsMatrix.subclass(*args_, **kwargs_) - else: - return RNAObsMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='RNAObsMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNAObsMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNAObsMatrix'): - super(RNAObsMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNAObsMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='RNAObsMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(RNAObsMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNAObsMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RNAObsMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNAObsMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.RNAMatrixObsRow(\n') - row_.exportLiteral(outfile, level, name_='RNAMatrixObsRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RNAObsMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = RNAMatrixObsRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class RNAObsMatrix - - -class RNASeqMatrix(AbstractSeqMatrix): - """A matrix of rows with seq strings of type RNA.""" - subclass = None - superclass = AbstractSeqMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(RNASeqMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if RNASeqMatrix.subclass: - return RNASeqMatrix.subclass(*args_, **kwargs_) - else: - return RNASeqMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='RNASeqMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNASeqMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNASeqMatrix'): - super(RNASeqMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNASeqMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='RNASeqMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(RNASeqMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNASeqMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RNASeqMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNASeqMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.RNAMatrixSeqRow(\n') - row_.exportLiteral(outfile, level, name_='RNAMatrixSeqRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RNASeqMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = RNAMatrixSeqRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class RNASeqMatrix - - -class RNAFormat(AbstractFormat): - """The RNAFormat class is the container of RNA column definitions.""" - subclass = None - superclass = AbstractFormat - def __init__(self, about=None, meta=None, states=None, char=None, set=None, valueOf_=None): - super(RNAFormat, self).__init__(about, meta, states, char, set, ) - if states is None: - self.states = [] - else: - self.states = states - if char is None: - self.char = [] - else: - self.char = char - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if RNAFormat.subclass: - return RNAFormat.subclass(*args_, **kwargs_) - else: - return RNAFormat(*args_, **kwargs_) - factory = staticmethod(factory) - def get_states(self): return self.states - def set_states(self, states): self.states = states - def add_states(self, value): self.states.append(value) - def insert_states(self, index, value): self.states[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def add_char(self, value): self.char.append(value) - def insert_char(self, index, value): self.char[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='RNAFormat', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNAFormat') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNAFormat'): - super(RNAFormat, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNAFormat') - def exportChildren(self, outfile, level, namespace_='', name_='RNAFormat', fromsubclass_=False): - for states_ in self.states: - states_.export(outfile, level, namespace_, name_='states') - for char_ in self.char: - char_.export(outfile, level, namespace_, name_='char') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.states or - self.char or - self.set or - super(RNAFormat, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNAFormat'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RNAFormat, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNAFormat, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('states=[\n') - level += 1 - for states_ in self.states: - showIndent(outfile, level) - outfile.write('model_.RNAStates(\n') - states_.exportLiteral(outfile, level, name_='RNAStates') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('char=[\n') - level += 1 - for char_ in self.char: - showIndent(outfile, level) - outfile.write('model_.RNAChar(\n') - char_.exportLiteral(outfile, level, name_='RNAChar') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CharSet(\n') - set_.exportLiteral(outfile, level, name_='CharSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RNAFormat, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'states': - obj_ = RNAStates.factory() - obj_.build(child_) - self.states.append(obj_) - elif nodeName_ == 'char': - obj_ = RNAChar.factory() - obj_.build(child_) - self.char.append(obj_) - elif nodeName_ == 'set': - obj_ = CharSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class RNAFormat - - -class RestrictionObsMatrix(AbstractObsMatrix): - """A matrix of rows with single character observations.""" - subclass = None - superclass = AbstractObsMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(RestrictionObsMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if RestrictionObsMatrix.subclass: - return RestrictionObsMatrix.subclass(*args_, **kwargs_) - else: - return RestrictionObsMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='RestrictionObsMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionObsMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RestrictionObsMatrix'): - super(RestrictionObsMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionObsMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='RestrictionObsMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(RestrictionObsMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RestrictionObsMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RestrictionObsMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RestrictionObsMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.RestrictionMatrixObsRow(\n') - row_.exportLiteral(outfile, level, name_='RestrictionMatrixObsRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RestrictionObsMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = RestrictionMatrixObsRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class RestrictionObsMatrix - - -class RestrictionSeqMatrix(AbstractSeqMatrix): - """A matrix of rows with seq strings of type restriction.""" - subclass = None - superclass = AbstractSeqMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(RestrictionSeqMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if RestrictionSeqMatrix.subclass: - return RestrictionSeqMatrix.subclass(*args_, **kwargs_) - else: - return RestrictionSeqMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='RestrictionSeqMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionSeqMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RestrictionSeqMatrix'): - super(RestrictionSeqMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionSeqMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='RestrictionSeqMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(RestrictionSeqMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RestrictionSeqMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RestrictionSeqMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RestrictionSeqMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.RestrictionMatrixSeqRow(\n') - row_.exportLiteral(outfile, level, name_='RestrictionMatrixSeqRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RestrictionSeqMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = RestrictionMatrixSeqRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class RestrictionSeqMatrix - - -class RestrictionFormat(AbstractFormat): - """The RestrictionFormat class is the container of restriction column - definitions.""" - subclass = None - superclass = AbstractFormat - def __init__(self, about=None, meta=None, states=None, char=None, set=None, valueOf_=None): - super(RestrictionFormat, self).__init__(about, meta, states, char, set, ) - if states is None: - self.states = [] - else: - self.states = states - if char is None: - self.char = [] - else: - self.char = char - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if RestrictionFormat.subclass: - return RestrictionFormat.subclass(*args_, **kwargs_) - else: - return RestrictionFormat(*args_, **kwargs_) - factory = staticmethod(factory) - def get_states(self): return self.states - def set_states(self, states): self.states = states - def add_states(self, value): self.states.append(value) - def insert_states(self, index, value): self.states[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def add_char(self, value): self.char.append(value) - def insert_char(self, index, value): self.char[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='RestrictionFormat', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionFormat') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RestrictionFormat'): - super(RestrictionFormat, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionFormat') - def exportChildren(self, outfile, level, namespace_='', name_='RestrictionFormat', fromsubclass_=False): - for states_ in self.states: - states_.export(outfile, level, namespace_, name_='states') - for char_ in self.char: - char_.export(outfile, level, namespace_, name_='char') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.states or - self.char or - self.set or - super(RestrictionFormat, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RestrictionFormat'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RestrictionFormat, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RestrictionFormat, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('states=[\n') - level += 1 - for states_ in self.states: - showIndent(outfile, level) - outfile.write('model_.RestrictionStates(\n') - states_.exportLiteral(outfile, level, name_='RestrictionStates') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('char=[\n') - level += 1 - for char_ in self.char: - showIndent(outfile, level) - outfile.write('model_.RestrictionChar(\n') - char_.exportLiteral(outfile, level, name_='RestrictionChar') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CharSet(\n') - set_.exportLiteral(outfile, level, name_='CharSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RestrictionFormat, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'states': - obj_ = RestrictionStates.factory() - obj_.build(child_) - self.states.append(obj_) - elif nodeName_ == 'char': - obj_ = RestrictionChar.factory() - obj_.build(child_) - self.char.append(obj_) - elif nodeName_ == 'set': - obj_ = CharSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class RestrictionFormat - - -class AAObsMatrix(AbstractObsMatrix): - """A matrix of rows with single character observations.""" - subclass = None - superclass = AbstractObsMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(AAObsMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AAObsMatrix.subclass: - return AAObsMatrix.subclass(*args_, **kwargs_) - else: - return AAObsMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AAObsMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AAObsMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AAObsMatrix'): - super(AAObsMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AAObsMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='AAObsMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(AAObsMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AAObsMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AAObsMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AAObsMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.AAMatrixObsRow(\n') - row_.exportLiteral(outfile, level, name_='AAMatrixObsRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AAObsMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = AAMatrixObsRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class AAObsMatrix - - -class AASeqMatrix(AbstractSeqMatrix): - """A matrix of rows with amino acid data as sequence strings.""" - subclass = None - superclass = AbstractSeqMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(AASeqMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AASeqMatrix.subclass: - return AASeqMatrix.subclass(*args_, **kwargs_) - else: - return AASeqMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AASeqMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AASeqMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AASeqMatrix'): - super(AASeqMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AASeqMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='AASeqMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(AASeqMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AASeqMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AASeqMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AASeqMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.AAMatrixSeqRow(\n') - row_.exportLiteral(outfile, level, name_='AAMatrixSeqRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AASeqMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = AAMatrixSeqRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class AASeqMatrix - - -class AAFormat(AbstractFormat): - """The AAFormat class is the container of amino acid column - definitions.""" - subclass = None - superclass = AbstractFormat - def __init__(self, about=None, meta=None, states=None, char=None, set=None, valueOf_=None): - super(AAFormat, self).__init__(about, meta, states, char, set, ) - if states is None: - self.states = [] - else: - self.states = states - if char is None: - self.char = [] - else: - self.char = char - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AAFormat.subclass: - return AAFormat.subclass(*args_, **kwargs_) - else: - return AAFormat(*args_, **kwargs_) - factory = staticmethod(factory) - def get_states(self): return self.states - def set_states(self, states): self.states = states - def add_states(self, value): self.states.append(value) - def insert_states(self, index, value): self.states[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def add_char(self, value): self.char.append(value) - def insert_char(self, index, value): self.char[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AAFormat', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AAFormat') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AAFormat'): - super(AAFormat, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AAFormat') - def exportChildren(self, outfile, level, namespace_='', name_='AAFormat', fromsubclass_=False): - for states_ in self.states: - states_.export(outfile, level, namespace_, name_='states') - for char_ in self.char: - char_.export(outfile, level, namespace_, name_='char') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.states or - self.char or - self.set or - super(AAFormat, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AAFormat'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AAFormat, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AAFormat, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('states=[\n') - level += 1 - for states_ in self.states: - showIndent(outfile, level) - outfile.write('model_.AAStates(\n') - states_.exportLiteral(outfile, level, name_='AAStates') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('char=[\n') - level += 1 - for char_ in self.char: - showIndent(outfile, level) - outfile.write('model_.AAChar(\n') - char_.exportLiteral(outfile, level, name_='AAChar') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CharSet(\n') - set_.exportLiteral(outfile, level, name_='CharSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AAFormat, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'states': - obj_ = AAStates.factory() - obj_.build(child_) - self.states.append(obj_) - elif nodeName_ == 'char': - obj_ = AAChar.factory() - obj_.build(child_) - self.char.append(obj_) - elif nodeName_ == 'set': - obj_ = CharSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class AAFormat - - -class DNAObsMatrix(AbstractObsMatrix): - """A matrix of rows with single character observations.""" - subclass = None - superclass = AbstractObsMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(DNAObsMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if DNAObsMatrix.subclass: - return DNAObsMatrix.subclass(*args_, **kwargs_) - else: - return DNAObsMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='DNAObsMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNAObsMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNAObsMatrix'): - super(DNAObsMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNAObsMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='DNAObsMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(DNAObsMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNAObsMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(DNAObsMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNAObsMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.DNAMatrixObsRow(\n') - row_.exportLiteral(outfile, level, name_='DNAMatrixObsRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(DNAObsMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = DNAMatrixObsRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class DNAObsMatrix - - -class DNASeqMatrix(AbstractSeqMatrix): - """A matrix of rows with seq strings of type DNA.""" - subclass = None - superclass = AbstractSeqMatrix - def __init__(self, about=None, meta=None, row=None, set=None, valueOf_=None): - super(DNASeqMatrix, self).__init__(about, meta, row, set, ) - if row is None: - self.row = [] - else: - self.row = row - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if DNASeqMatrix.subclass: - return DNASeqMatrix.subclass(*args_, **kwargs_) - else: - return DNASeqMatrix(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def add_row(self, value): self.row.append(value) - def insert_row(self, index, value): self.row[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='DNASeqMatrix', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNASeqMatrix') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNASeqMatrix'): - super(DNASeqMatrix, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNASeqMatrix') - def exportChildren(self, outfile, level, namespace_='', name_='DNASeqMatrix', fromsubclass_=False): - for row_ in self.row: - row_.export(outfile, level, namespace_, name_='row') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.row or - self.set or - super(DNASeqMatrix, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNASeqMatrix'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(DNASeqMatrix, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNASeqMatrix, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('row=[\n') - level += 1 - for row_ in self.row: - showIndent(outfile, level) - outfile.write('model_.DNAMatrixSeqRow(\n') - row_.exportLiteral(outfile, level, name_='DNAMatrixSeqRow') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.RowSet(\n') - set_.exportLiteral(outfile, level, name_='RowSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(DNASeqMatrix, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'row': - obj_ = DNAMatrixSeqRow.factory() - obj_.build(child_) - self.row.append(obj_) - elif nodeName_ == 'set': - obj_ = RowSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class DNASeqMatrix - - -class DNAFormat(AbstractFormat): - """The DNAFormat class is the container of DNA column definitions.""" - subclass = None - superclass = AbstractFormat - def __init__(self, about=None, meta=None, states=None, char=None, set=None, valueOf_=None): - super(DNAFormat, self).__init__(about, meta, states, char, set, ) - if states is None: - self.states = [] - else: - self.states = states - if char is None: - self.char = [] - else: - self.char = char - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if DNAFormat.subclass: - return DNAFormat.subclass(*args_, **kwargs_) - else: - return DNAFormat(*args_, **kwargs_) - factory = staticmethod(factory) - def get_states(self): return self.states - def set_states(self, states): self.states = states - def add_states(self, value): self.states.append(value) - def insert_states(self, index, value): self.states[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def add_char(self, value): self.char.append(value) - def insert_char(self, index, value): self.char[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='DNAFormat', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNAFormat') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNAFormat'): - super(DNAFormat, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNAFormat') - def exportChildren(self, outfile, level, namespace_='', name_='DNAFormat', fromsubclass_=False): - for states_ in self.states: - states_.export(outfile, level, namespace_, name_='states') - for char_ in self.char: - char_.export(outfile, level, namespace_, name_='char') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.states or - self.char or - self.set or - super(DNAFormat, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNAFormat'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(DNAFormat, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNAFormat, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('states=[\n') - level += 1 - for states_ in self.states: - showIndent(outfile, level) - outfile.write('model_.DNAStates(\n') - states_.exportLiteral(outfile, level, name_='DNAStates') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('char=[\n') - level += 1 - for char_ in self.char: - showIndent(outfile, level) - outfile.write('model_.DNAChar(\n') - char_.exportLiteral(outfile, level, name_='DNAChar') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CharSet(\n') - set_.exportLiteral(outfile, level, name_='CharSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(DNAFormat, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'states': - obj_ = DNAStates.factory() - obj_.build(child_) - self.states.append(obj_) - elif nodeName_ == 'char': - obj_ = DNAChar.factory() - obj_.build(child_) - self.char.append(obj_) - elif nodeName_ == 'set': - obj_ = CharSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class DNAFormat - - -class AbstractObs(Labelled): - """The AbstractObs type is the superclass for single observations, i.e. - cells in a matrix. A concrete instance of AbstractObs has a - "char" attribute that refers to an explicitly defined character - (e.g. in categorical matrices), and a "state" attribute that - either holds a reference to an explicitly defined state, or a - raw state value (a continuous value).""" - subclass = None - superclass = Labelled - def __init__(self, about=None, meta=None, label=None, char=None, state=None, valueOf_=None): - super(AbstractObs, self).__init__(about, meta, label, ) - self.char = _cast(None, char) - self.state = _cast(None, state) - pass - def factory(*args_, **kwargs_): - if AbstractObs.subclass: - return AbstractObs.subclass(*args_, **kwargs_) - else: - return AbstractObs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_char(self): return self.char - def set_char(self, char): self.char = char - def get_state(self): return self.state - def set_state(self, state): self.state = state - def export(self, outfile, level, namespace_='', name_='AbstractObs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractObs') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractObs"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractObs'): - super(AbstractObs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractObs') - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - outfile.write(' char=%s' % (quote_attrib(self.char), )) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - outfile.write(' state=%s' % (quote_attrib(self.state), )) - def exportChildren(self, outfile, level, namespace_='', name_='AbstractObs', fromsubclass_=False): - super(AbstractObs, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(AbstractObs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractObs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - showIndent(outfile, level) - outfile.write('char = %s,\n' % (self.char,)) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - showIndent(outfile, level) - outfile.write('state = %s,\n' % (self.state,)) - super(AbstractObs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractObs, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('char', node) - if value is not None and 'char' not in already_processed: - already_processed.append('char') - self.char = value - value = find_attr_value_('state', node) - if value is not None and 'state' not in already_processed: - already_processed.append('state') - self.state = value - super(AbstractObs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(AbstractObs, self).buildChildren(child_, node, nodeName_, True) - pass -# end class AbstractObs - - -class ContinuousObs(AbstractObs): - """This is a single cell in a matrix containing a continuous - observation.""" - subclass = None - superclass = AbstractObs - def __init__(self, about=None, meta=None, label=None, char=None, state=None, valueOf_=None): - super(ContinuousObs, self).__init__(about, meta, label, char, state, ) - self.char = _cast(None, char) - self.state = _cast(None, state) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if ContinuousObs.subclass: - return ContinuousObs.subclass(*args_, **kwargs_) - else: - return ContinuousObs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def get_state(self): return self.state - def set_state(self, state): self.state = state - def validate_ContinuousToken(self, value): - # Validate type ContinuousToken, a restriction on xs:double. - pass - def export(self, outfile, level, namespace_='', name_='ContinuousObs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousObs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ContinuousObs'): - super(ContinuousObs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousObs') - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - outfile.write(' char=%s' % (self.gds_format_string(quote_attrib(self.char).encode(ExternalEncoding), input_name='char'), )) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - outfile.write(' state=%s' % (quote_attrib(self.state), )) - def exportChildren(self, outfile, level, namespace_='', name_='ContinuousObs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(ContinuousObs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ContinuousObs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - showIndent(outfile, level) - outfile.write('char = "%s",\n' % (self.char,)) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - showIndent(outfile, level) - outfile.write('state = %e,\n' % (self.state,)) - super(ContinuousObs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ContinuousObs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('char', node) - if value is not None and 'char' not in already_processed: - already_processed.append('char') - self.char = value - value = find_attr_value_('state', node) - if value is not None and 'state' not in already_processed: - already_processed.append('state') - try: - self.state = float(value) - except ValueError, exp: - raise ValueError('Bad float/double attribute (state): %s' % exp) - self.validate_ContinuousToken(self.state) # validate type ContinuousToken - super(ContinuousObs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class ContinuousObs - - -class IDTagged(Labelled): - """The IDTagged complexType is a super class for objects that require - unique id attributes of type xs:ID. The id must be unique within - the XML document.""" - subclass = None - superclass = Labelled - def __init__(self, about=None, meta=None, label=None, id=None, valueOf_=None): - super(IDTagged, self).__init__(about, meta, label, ) - self.id = _cast(None, id) - pass - def factory(*args_, **kwargs_): - if IDTagged.subclass: - return IDTagged.subclass(*args_, **kwargs_) - else: - return IDTagged(*args_, **kwargs_) - factory = staticmethod(factory) - def get_id(self): return self.id - def set_id(self, id): self.id = id - def export(self, outfile, level, namespace_='', name_='IDTagged', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='IDTagged') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="IDTagged"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='IDTagged'): - super(IDTagged, self).exportAttributes(outfile, level, already_processed, namespace_, name_='IDTagged') - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) - def exportChildren(self, outfile, level, namespace_='', name_='IDTagged', fromsubclass_=False): - super(IDTagged, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(IDTagged, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='IDTagged'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = "%s",\n' % (self.id,)) - super(IDTagged, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(IDTagged, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - self.id = value - super(IDTagged, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(IDTagged, self).buildChildren(child_, node, nodeName_, True) - pass -# end class IDTagged - - -class Taxa(IDTagged): - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, set=None, valueOf_=None): - super(Taxa, self).__init__(about, meta, label, id, ) - if otu is None: - self.otu = [] - else: - self.otu = otu - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if Taxa.subclass: - return Taxa.subclass(*args_, **kwargs_) - else: - return Taxa(*args_, **kwargs_) - factory = staticmethod(factory) - def get_otu(self): return self.otu - def set_otu(self, otu): self.otu = otu - def add_otu(self, value): self.otu.append(value) - def insert_otu(self, index, value): self.otu[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='Taxa', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Taxa') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="Taxa"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='Taxa'): - super(Taxa, self).exportAttributes(outfile, level, already_processed, namespace_, name_='Taxa') - def exportChildren(self, outfile, level, namespace_='', name_='Taxa', fromsubclass_=False): - super(Taxa, self).exportChildren(outfile, level, namespace_, name_, True) - for otu_ in self.otu: - otu_.export(outfile, level, namespace_, name_='otu') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.otu or - self.set or - super(Taxa, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Taxa'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(Taxa, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(Taxa, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('otu=[\n') - level += 1 - for otu_ in self.otu: - showIndent(outfile, level) - outfile.write('model_.Taxon(\n') - otu_.exportLiteral(outfile, level, name_='Taxon') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.TaxonSet(\n') - set_.exportLiteral(outfile, level, name_='TaxonSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(Taxa, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'otu': - obj_ = Taxon.factory() - obj_.build(child_) - self.otu.append(obj_) - elif nodeName_ == 'set': - obj_ = TaxonSet.factory() - obj_.build(child_) - self.set.append(obj_) - super(Taxa, self).buildChildren(child_, node, nodeName_, True) -# end class Taxa - - -class Taxon(IDTagged): - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, valueOf_=None): - super(Taxon, self).__init__(about, meta, label, id, ) - pass - def factory(*args_, **kwargs_): - if Taxon.subclass: - return Taxon.subclass(*args_, **kwargs_) - else: - return Taxon(*args_, **kwargs_) - factory = staticmethod(factory) - def export(self, outfile, level, namespace_='', name_='Taxon', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Taxon') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="Taxon"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='Taxon'): - super(Taxon, self).exportAttributes(outfile, level, already_processed, namespace_, name_='Taxon') - def exportChildren(self, outfile, level, namespace_='', name_='Taxon', fromsubclass_=False): - super(Taxon, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(Taxon, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Taxon'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(Taxon, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(Taxon, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(Taxon, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(Taxon, self).buildChildren(child_, node, nodeName_, True) - pass -# end class Taxon - - -class AbstractTrees(IDTagged): - """The AbstractTrees superclass is what concrete trees inherit from.""" - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, network=None, tree=None, set=None, valueOf_=None): - super(AbstractTrees, self).__init__(about, meta, label, id, ) - if network is None: - self.network = [] - else: - self.network = network - if tree is None: - self.tree = [] - else: - self.tree = tree - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AbstractTrees.subclass: - return AbstractTrees.subclass(*args_, **kwargs_) - else: - return AbstractTrees(*args_, **kwargs_) - factory = staticmethod(factory) - def get_network(self): return self.network - def set_network(self, network): self.network = network - def add_network(self, value): self.network.append(value) - def insert_network(self, index, value): self.network[index] = value - def get_tree(self): return self.tree - def set_tree(self, tree): self.tree = tree - def add_tree(self, value): self.tree.append(value) - def insert_tree(self, index, value): self.tree[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AbstractTrees', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractTrees') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractTrees"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractTrees'): - super(AbstractTrees, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractTrees') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractTrees', fromsubclass_=False): - super(AbstractTrees, self).exportChildren(outfile, level, namespace_, name_, True) - for network_ in self.get_network(): - network_.export(outfile, level, namespace_, name_='network') - for tree_ in self.get_tree(): - tree_.export(outfile, level, namespace_, name_='tree') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.network or - self.tree or - self.set or - super(AbstractTrees, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractTrees'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractTrees, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractTrees, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('network=[\n') - level += 1 - for network_ in self.network: - showIndent(outfile, level) - outfile.write('model_.AbstractNetwork(\n') - network_.exportLiteral(outfile, level, name_='AbstractNetwork') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('tree=[\n') - level += 1 - for tree_ in self.tree: - showIndent(outfile, level) - outfile.write('model_.AbstractTree(\n') - tree_.exportLiteral(outfile, level, name_='AbstractTree') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.TreeAndNetworkSet(\n') - set_.exportLiteral(outfile, level, name_='TreeAndNetworkSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractTrees, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'network': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.network.append(obj_) - elif nodeName_ == 'tree': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.tree.append(obj_) - elif nodeName_ == 'set': - obj_ = TreeAndNetworkSet.factory() - obj_.build(child_) - self.set.append(obj_) - super(AbstractTrees, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractTrees - - -class AbstractNetwork(IDTagged): - """The AbstractNetwork superclass is what a concrete network inherits - from.""" - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, node=None, edge=None, set=None, valueOf_=None): - super(AbstractNetwork, self).__init__(about, meta, label, id, ) - if node is None: - self.node = [] - else: - self.node = node - if edge is None: - self.edge = [] - else: - self.edge = edge - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AbstractNetwork.subclass: - return AbstractNetwork.subclass(*args_, **kwargs_) - else: - return AbstractNetwork(*args_, **kwargs_) - factory = staticmethod(factory) - def get_node(self): return self.node - def set_node(self, node): self.node = node - def add_node(self, value): self.node.append(value) - def insert_node(self, index, value): self.node[index] = value - def get_edge(self): return self.edge - def set_edge(self, edge): self.edge = edge - def add_edge(self, value): self.edge.append(value) - def insert_edge(self, index, value): self.edge[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AbstractNetwork', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractNetwork') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractNetwork"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractNetwork'): - super(AbstractNetwork, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractNetwork') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractNetwork', fromsubclass_=False): - super(AbstractNetwork, self).exportChildren(outfile, level, namespace_, name_, True) - for node_ in self.get_node(): - node_.export(outfile, level, namespace_, name_='node') - for edge_ in self.get_edge(): - edge_.export(outfile, level, namespace_, name_='edge') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.node or - self.edge or - self.set or - super(AbstractNetwork, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractNetwork'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractNetwork, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractNetwork, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('node=[\n') - level += 1 - for node_ in self.node: - showIndent(outfile, level) - outfile.write('model_.AbstractNode(\n') - node_.exportLiteral(outfile, level, name_='AbstractNode') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('edge=[\n') - level += 1 - for edge_ in self.edge: - showIndent(outfile, level) - outfile.write('model_.AbstractEdge(\n') - edge_.exportLiteral(outfile, level, name_='AbstractEdge') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.NodeAndRootEdgeAndEdgeSet(\n') - set_.exportLiteral(outfile, level, name_='NodeAndRootEdgeAndEdgeSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractNetwork, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'node': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.node.append(obj_) - elif nodeName_ == 'edge': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.edge.append(obj_) - elif nodeName_ == 'set': - obj_ = NodeAndRootEdgeAndEdgeSet.factory() - obj_.build(child_) - self.set.append(obj_) - super(AbstractNetwork, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractNetwork - - -class AbstractTree(IDTagged): - """The AbstractTree superclass is what a concrete tree inherits from.""" - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, node=None, rootedge=None, edge=None, set=None, valueOf_=None): - super(AbstractTree, self).__init__(about, meta, label, id, ) - if node is None: - self.node = [] - else: - self.node = node - self.rootedge = rootedge - if edge is None: - self.edge = [] - else: - self.edge = edge - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AbstractTree.subclass: - return AbstractTree.subclass(*args_, **kwargs_) - else: - return AbstractTree(*args_, **kwargs_) - factory = staticmethod(factory) - def get_node(self): return self.node - def set_node(self, node): self.node = node - def add_node(self, value): self.node.append(value) - def insert_node(self, index, value): self.node[index] = value - def get_rootedge(self): return self.rootedge - def set_rootedge(self, rootedge): self.rootedge = rootedge - def get_edge(self): return self.edge - def set_edge(self, edge): self.edge = edge - def add_edge(self, value): self.edge.append(value) - def insert_edge(self, index, value): self.edge[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AbstractTree', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractTree') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractTree"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractTree'): - super(AbstractTree, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractTree') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractTree', fromsubclass_=False): - super(AbstractTree, self).exportChildren(outfile, level, namespace_, name_, True) - for node_ in self.get_node(): - node_.export(outfile, level, namespace_, name_='node') - rootedge_.export(outfile, level, namespace_, name_='rootedge') - for edge_ in self.get_edge(): - edge_.export(outfile, level, namespace_, name_='edge') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.node or - self.rootedge is not None or - self.edge or - self.set or - super(AbstractTree, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractTree'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractTree, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractTree, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('node=[\n') - level += 1 - for node_ in self.node: - showIndent(outfile, level) - outfile.write('model_.AbstractNode(\n') - node_.exportLiteral(outfile, level, name_='AbstractNode') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.AbstractRootEdge is not None: - showIndent(outfile, level) - outfile.write('AbstractRootEdge=model_.AbstractRootEdge(\n') - self.AbstractRootEdge.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - showIndent(outfile, level) - outfile.write('edge=[\n') - level += 1 - for edge_ in self.edge: - showIndent(outfile, level) - outfile.write('model_.AbstractEdge(\n') - edge_.exportLiteral(outfile, level, name_='AbstractEdge') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.NodeAndRootEdgeAndEdgeSet(\n') - set_.exportLiteral(outfile, level, name_='NodeAndRootEdgeAndEdgeSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractTree, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'node': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.node.append(obj_) - elif nodeName_ == 'rootedge': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.set_rootedge(obj_) - elif nodeName_ == 'edge': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.edge.append(obj_) - elif nodeName_ == 'set': - obj_ = NodeAndRootEdgeAndEdgeSet.factory() - obj_.build(child_) - self.set.append(obj_) - super(AbstractTree, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractTree - - -class AbstractRootEdge(IDTagged): - """The AbstractRootEdge complex type is a superclass for the edge that - leads into a root, i.e. an edge with only a target attribute, - but no source attribute. This type of edge is used for - coalescent trees, where the initial lineage has a certain length - before things start splitting up.""" - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, length=None, target=None, valueOf_=None): - super(AbstractRootEdge, self).__init__(about, meta, label, id, ) - self.length = _cast(None, length) - self.target = _cast(None, target) - pass - def factory(*args_, **kwargs_): - if AbstractRootEdge.subclass: - return AbstractRootEdge.subclass(*args_, **kwargs_) - else: - return AbstractRootEdge(*args_, **kwargs_) - factory = staticmethod(factory) - def get_length(self): return self.length - def set_length(self, length): self.length = length - def get_target(self): return self.target - def set_target(self, target): self.target = target - def export(self, outfile, level, namespace_='', name_='AbstractRootEdge', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractRootEdge') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractRootEdge"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractRootEdge'): - super(AbstractRootEdge, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractRootEdge') - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - outfile.write(' length=%s' % (quote_attrib(self.length), )) - if self.target is not None and 'target' not in already_processed: - already_processed.append('target') - outfile.write(' target=%s' % (self.gds_format_string(quote_attrib(self.target).encode(ExternalEncoding), input_name='target'), )) - def exportChildren(self, outfile, level, namespace_='', name_='AbstractRootEdge', fromsubclass_=False): - super(AbstractRootEdge, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(AbstractRootEdge, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractRootEdge'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - showIndent(outfile, level) - outfile.write('length = %s,\n' % (self.length,)) - if self.target is not None and 'target' not in already_processed: - already_processed.append('target') - showIndent(outfile, level) - outfile.write('target = "%s",\n' % (self.target,)) - super(AbstractRootEdge, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractRootEdge, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('length', node) - if value is not None and 'length' not in already_processed: - already_processed.append('length') - self.length = value - value = find_attr_value_('target', node) - if value is not None and 'target' not in already_processed: - already_processed.append('target') - self.target = value - super(AbstractRootEdge, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(AbstractRootEdge, self).buildChildren(child_, node, nodeName_, True) - pass -# end class AbstractRootEdge - - -class AbstractEdge(IDTagged): - """The AbstractEdge superclass is what concrete edges inherit from by - restriction. It represents an edge element much like that of - GraphML, i.e. an element that connects node elements.""" - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, source=None, length=None, target=None, valueOf_=None): - super(AbstractEdge, self).__init__(about, meta, label, id, ) - self.source = _cast(None, source) - self.length = _cast(None, length) - self.target = _cast(None, target) - pass - def factory(*args_, **kwargs_): - if AbstractEdge.subclass: - return AbstractEdge.subclass(*args_, **kwargs_) - else: - return AbstractEdge(*args_, **kwargs_) - factory = staticmethod(factory) - def get_source(self): return self.source - def set_source(self, source): self.source = source - def get_length(self): return self.length - def set_length(self, length): self.length = length - def get_target(self): return self.target - def set_target(self, target): self.target = target - def export(self, outfile, level, namespace_='', name_='AbstractEdge', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractEdge') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractEdge"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractEdge'): - super(AbstractEdge, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractEdge') - if self.source is not None and 'source' not in already_processed: - already_processed.append('source') - outfile.write(' source=%s' % (self.gds_format_string(quote_attrib(self.source).encode(ExternalEncoding), input_name='source'), )) - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - outfile.write(' length=%s' % (quote_attrib(self.length), )) - if self.target is not None and 'target' not in already_processed: - already_processed.append('target') - outfile.write(' target=%s' % (self.gds_format_string(quote_attrib(self.target).encode(ExternalEncoding), input_name='target'), )) - def exportChildren(self, outfile, level, namespace_='', name_='AbstractEdge', fromsubclass_=False): - super(AbstractEdge, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(AbstractEdge, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractEdge'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.source is not None and 'source' not in already_processed: - already_processed.append('source') - showIndent(outfile, level) - outfile.write('source = "%s",\n' % (self.source,)) - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - showIndent(outfile, level) - outfile.write('length = %s,\n' % (self.length,)) - if self.target is not None and 'target' not in already_processed: - already_processed.append('target') - showIndent(outfile, level) - outfile.write('target = "%s",\n' % (self.target,)) - super(AbstractEdge, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractEdge, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('source', node) - if value is not None and 'source' not in already_processed: - already_processed.append('source') - self.source = value - value = find_attr_value_('length', node) - if value is not None and 'length' not in already_processed: - already_processed.append('length') - self.length = value - value = find_attr_value_('target', node) - if value is not None and 'target' not in already_processed: - already_processed.append('target') - self.target = value - super(AbstractEdge, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(AbstractEdge, self).buildChildren(child_, node, nodeName_, True) - pass -# end class AbstractEdge - - -class IntTree(AbstractTree): - """A concrete tree implementation, with integer edge lengths.""" - subclass = None - superclass = AbstractTree - def __init__(self, about=None, meta=None, label=None, id=None, node=None, rootedge=None, edge=None, set=None, valueOf_=None): - super(IntTree, self).__init__(about, meta, label, id, node, rootedge, edge, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if node is None: - self.node = [] - else: - self.node = node - self.rootedge = rootedge - if edge is None: - self.edge = [] - else: - self.edge = edge - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if IntTree.subclass: - return IntTree.subclass(*args_, **kwargs_) - else: - return IntTree(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_node(self): return self.node - def set_node(self, node): self.node = node - def add_node(self, value): self.node.append(value) - def insert_node(self, index, value): self.node[index] = value - def get_rootedge(self): return self.rootedge - def set_rootedge(self, rootedge): self.rootedge = rootedge - def get_edge(self): return self.edge - def set_edge(self, edge): self.edge = edge - def add_edge(self, value): self.edge.append(value) - def insert_edge(self, index, value): self.edge[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='IntTree', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='IntTree') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='IntTree'): - super(IntTree, self).exportAttributes(outfile, level, already_processed, namespace_, name_='IntTree') - def exportChildren(self, outfile, level, namespace_='', name_='IntTree', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for node_ in self.node: - node_.export(outfile, level, namespace_, name_='node') - if self.rootedge: - self.rootedge.export(outfile, level, namespace_, name_='rootedge') - for edge_ in self.edge: - edge_.export(outfile, level, namespace_, name_='edge') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.node or - self.rootedge is not None or - self.edge or - self.set or - super(IntTree, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='IntTree'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(IntTree, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(IntTree, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('node=[\n') - level += 1 - for node_ in self.node: - showIndent(outfile, level) - outfile.write('model_.TreeNode(\n') - node_.exportLiteral(outfile, level, name_='TreeNode') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.rootedge is not None: - showIndent(outfile, level) - outfile.write('rootedge=model_.TreeIntRootEdge(\n') - self.rootedge.exportLiteral(outfile, level, name_='rootedge') - showIndent(outfile, level) - outfile.write('),\n') - showIndent(outfile, level) - outfile.write('edge=[\n') - level += 1 - for edge_ in self.edge: - showIndent(outfile, level) - outfile.write('model_.TreeIntEdge(\n') - edge_.exportLiteral(outfile, level, name_='TreeIntEdge') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.NodeAndRootEdgeAndEdgeSet(\n') - set_.exportLiteral(outfile, level, name_='NodeAndRootEdgeAndEdgeSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(IntTree, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'node': - obj_ = TreeNode.factory() - obj_.build(child_) - self.node.append(obj_) - elif nodeName_ == 'rootedge': - obj_ = TreeIntRootEdge.factory() - obj_.build(child_) - self.set_rootedge(obj_) - elif nodeName_ == 'edge': - obj_ = TreeIntEdge.factory() - obj_.build(child_) - self.edge.append(obj_) - elif nodeName_ == 'set': - obj_ = NodeAndRootEdgeAndEdgeSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class IntTree - - -class FloatTree(AbstractTree): - """A concrete tree implementation, with floating point edge lengths.""" - subclass = None - superclass = AbstractTree - def __init__(self, about=None, meta=None, label=None, id=None, node=None, rootedge=None, edge=None, set=None, valueOf_=None): - super(FloatTree, self).__init__(about, meta, label, id, node, rootedge, edge, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if node is None: - self.node = [] - else: - self.node = node - self.rootedge = rootedge - if edge is None: - self.edge = [] - else: - self.edge = edge - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if FloatTree.subclass: - return FloatTree.subclass(*args_, **kwargs_) - else: - return FloatTree(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_node(self): return self.node - def set_node(self, node): self.node = node - def add_node(self, value): self.node.append(value) - def insert_node(self, index, value): self.node[index] = value - def get_rootedge(self): return self.rootedge - def set_rootedge(self, rootedge): self.rootedge = rootedge - def get_edge(self): return self.edge - def set_edge(self, edge): self.edge = edge - def add_edge(self, value): self.edge.append(value) - def insert_edge(self, index, value): self.edge[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='FloatTree', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='FloatTree') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='FloatTree'): - super(FloatTree, self).exportAttributes(outfile, level, already_processed, namespace_, name_='FloatTree') - def exportChildren(self, outfile, level, namespace_='', name_='FloatTree', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for node_ in self.node: - node_.export(outfile, level, namespace_, name_='node') - if self.rootedge: - self.rootedge.export(outfile, level, namespace_, name_='rootedge') - for edge_ in self.edge: - edge_.export(outfile, level, namespace_, name_='edge') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.node or - self.rootedge is not None or - self.edge or - self.set or - super(FloatTree, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='FloatTree'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(FloatTree, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(FloatTree, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('node=[\n') - level += 1 - for node_ in self.node: - showIndent(outfile, level) - outfile.write('model_.TreeNode(\n') - node_.exportLiteral(outfile, level, name_='TreeNode') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.rootedge is not None: - showIndent(outfile, level) - outfile.write('rootedge=model_.TreeFloatRootEdge(\n') - self.rootedge.exportLiteral(outfile, level, name_='rootedge') - showIndent(outfile, level) - outfile.write('),\n') - showIndent(outfile, level) - outfile.write('edge=[\n') - level += 1 - for edge_ in self.edge: - showIndent(outfile, level) - outfile.write('model_.TreeFloatEdge(\n') - edge_.exportLiteral(outfile, level, name_='TreeFloatEdge') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.NodeAndRootEdgeAndEdgeSet(\n') - set_.exportLiteral(outfile, level, name_='NodeAndRootEdgeAndEdgeSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(FloatTree, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'node': - obj_ = TreeNode.factory() - obj_.build(child_) - self.node.append(obj_) - elif nodeName_ == 'rootedge': - obj_ = TreeFloatRootEdge.factory() - obj_.build(child_) - self.set_rootedge(obj_) - elif nodeName_ == 'edge': - obj_ = TreeFloatEdge.factory() - obj_.build(child_) - self.edge.append(obj_) - elif nodeName_ == 'set': - obj_ = NodeAndRootEdgeAndEdgeSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class FloatTree - - -class TreeIntRootEdge(AbstractRootEdge): - """A concrete root edge implementation, with int length.""" - subclass = None - superclass = AbstractRootEdge - def __init__(self, about=None, meta=None, label=None, id=None, length=None, target=None, valueOf_=None): - super(TreeIntRootEdge, self).__init__(about, meta, label, id, length, target, ) - self.length = _cast(int, length) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if TreeIntRootEdge.subclass: - return TreeIntRootEdge.subclass(*args_, **kwargs_) - else: - return TreeIntRootEdge(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_length(self): return self.length - def set_length(self, length): self.length = length - def export(self, outfile, level, namespace_='', name_='TreeIntRootEdge', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='TreeIntRootEdge') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='TreeIntRootEdge'): - super(TreeIntRootEdge, self).exportAttributes(outfile, level, already_processed, namespace_, name_='TreeIntRootEdge') - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - outfile.write(' length="%s"' % self.gds_format_integer(self.length, input_name='length')) - def exportChildren(self, outfile, level, namespace_='', name_='TreeIntRootEdge', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(TreeIntRootEdge, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='TreeIntRootEdge'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - showIndent(outfile, level) - outfile.write('length = %d,\n' % (self.length,)) - super(TreeIntRootEdge, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(TreeIntRootEdge, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('length', node) - if value is not None and 'length' not in already_processed: - already_processed.append('length') - try: - self.length = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - super(TreeIntRootEdge, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class TreeIntRootEdge - - -class TreeIntEdge(AbstractEdge): - """A concrete edge implementation, with int length.""" - subclass = None - superclass = AbstractEdge - def __init__(self, about=None, meta=None, label=None, id=None, source=None, length=None, target=None, valueOf_=None): - super(TreeIntEdge, self).__init__(about, meta, label, id, source, length, target, ) - self.length = _cast(int, length) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if TreeIntEdge.subclass: - return TreeIntEdge.subclass(*args_, **kwargs_) - else: - return TreeIntEdge(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_length(self): return self.length - def set_length(self, length): self.length = length - def export(self, outfile, level, namespace_='', name_='TreeIntEdge', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='TreeIntEdge') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='TreeIntEdge'): - super(TreeIntEdge, self).exportAttributes(outfile, level, already_processed, namespace_, name_='TreeIntEdge') - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - outfile.write(' length="%s"' % self.gds_format_integer(self.length, input_name='length')) - def exportChildren(self, outfile, level, namespace_='', name_='TreeIntEdge', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(TreeIntEdge, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='TreeIntEdge'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - showIndent(outfile, level) - outfile.write('length = %d,\n' % (self.length,)) - super(TreeIntEdge, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(TreeIntEdge, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('length', node) - if value is not None and 'length' not in already_processed: - already_processed.append('length') - try: - self.length = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - super(TreeIntEdge, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class TreeIntEdge - - -class TreeFloatRootEdge(AbstractRootEdge): - """A concrete root edge implementation, with float length.""" - subclass = None - superclass = AbstractRootEdge - def __init__(self, about=None, meta=None, label=None, id=None, length=None, target=None, valueOf_=None): - super(TreeFloatRootEdge, self).__init__(about, meta, label, id, length, target, ) - self.length = _cast(float, length) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if TreeFloatRootEdge.subclass: - return TreeFloatRootEdge.subclass(*args_, **kwargs_) - else: - return TreeFloatRootEdge(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_length(self): return self.length - def set_length(self, length): self.length = length - def export(self, outfile, level, namespace_='', name_='TreeFloatRootEdge', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='TreeFloatRootEdge') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='TreeFloatRootEdge'): - super(TreeFloatRootEdge, self).exportAttributes(outfile, level, already_processed, namespace_, name_='TreeFloatRootEdge') - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - outfile.write(' length="%s"' % self.gds_format_double(self.length, input_name='length')) - def exportChildren(self, outfile, level, namespace_='', name_='TreeFloatRootEdge', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(TreeFloatRootEdge, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='TreeFloatRootEdge'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - showIndent(outfile, level) - outfile.write('length = %e,\n' % (self.length,)) - super(TreeFloatRootEdge, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(TreeFloatRootEdge, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('length', node) - if value is not None and 'length' not in already_processed: - already_processed.append('length') - try: - self.length = float(value) - except ValueError, exp: - raise ValueError('Bad float/double attribute (length): %s' % exp) - super(TreeFloatRootEdge, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class TreeFloatRootEdge - - -class TreeFloatEdge(AbstractEdge): - """A concrete edge implementation, with float length.""" - subclass = None - superclass = AbstractEdge - def __init__(self, about=None, meta=None, label=None, id=None, source=None, length=None, target=None, valueOf_=None): - super(TreeFloatEdge, self).__init__(about, meta, label, id, source, length, target, ) - self.length = _cast(float, length) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if TreeFloatEdge.subclass: - return TreeFloatEdge.subclass(*args_, **kwargs_) - else: - return TreeFloatEdge(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_length(self): return self.length - def set_length(self, length): self.length = length - def export(self, outfile, level, namespace_='', name_='TreeFloatEdge', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='TreeFloatEdge') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='TreeFloatEdge'): - super(TreeFloatEdge, self).exportAttributes(outfile, level, already_processed, namespace_, name_='TreeFloatEdge') - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - outfile.write(' length="%s"' % self.gds_format_double(self.length, input_name='length')) - def exportChildren(self, outfile, level, namespace_='', name_='TreeFloatEdge', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(TreeFloatEdge, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='TreeFloatEdge'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - showIndent(outfile, level) - outfile.write('length = %e,\n' % (self.length,)) - super(TreeFloatEdge, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(TreeFloatEdge, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('length', node) - if value is not None and 'length' not in already_processed: - already_processed.append('length') - try: - self.length = float(value) - except ValueError, exp: - raise ValueError('Bad float/double attribute (length): %s' % exp) - super(TreeFloatEdge, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class TreeFloatEdge - - -class StandardObs(AbstractObs): - """This is a single cell in a matrix containing a standard observation.""" - subclass = None - superclass = AbstractObs - def __init__(self, about=None, meta=None, label=None, char=None, state=None, valueOf_=None): - super(StandardObs, self).__init__(about, meta, label, char, state, ) - self.char = _cast(None, char) - self.state = _cast(None, state) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if StandardObs.subclass: - return StandardObs.subclass(*args_, **kwargs_) - else: - return StandardObs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def get_state(self): return self.state - def set_state(self, state): self.state = state - def export(self, outfile, level, namespace_='', name_='StandardObs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardObs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardObs'): - super(StandardObs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardObs') - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - outfile.write(' char=%s' % (self.gds_format_string(quote_attrib(self.char).encode(ExternalEncoding), input_name='char'), )) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - outfile.write(' state=%s' % (self.gds_format_string(quote_attrib(self.state).encode(ExternalEncoding), input_name='state'), )) - def exportChildren(self, outfile, level, namespace_='', name_='StandardObs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(StandardObs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardObs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - showIndent(outfile, level) - outfile.write('char = "%s",\n' % (self.char,)) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - showIndent(outfile, level) - outfile.write('state = "%s",\n' % (self.state,)) - super(StandardObs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardObs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('char', node) - if value is not None and 'char' not in already_processed: - already_processed.append('char') - self.char = value - value = find_attr_value_('state', node) - if value is not None and 'state' not in already_processed: - already_processed.append('state') - self.state = value - super(StandardObs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class StandardObs - - -class RNAObs(AbstractObs): - """This is a single cell in a matrix containing an RNA nucleotide - observation.""" - subclass = None - superclass = AbstractObs - def __init__(self, about=None, meta=None, label=None, char=None, state=None, valueOf_=None): - super(RNAObs, self).__init__(about, meta, label, char, state, ) - self.char = _cast(None, char) - self.state = _cast(None, state) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if RNAObs.subclass: - return RNAObs.subclass(*args_, **kwargs_) - else: - return RNAObs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def get_state(self): return self.state - def set_state(self, state): self.state = state - def export(self, outfile, level, namespace_='', name_='RNAObs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNAObs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNAObs'): - super(RNAObs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNAObs') - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - outfile.write(' char=%s' % (self.gds_format_string(quote_attrib(self.char).encode(ExternalEncoding), input_name='char'), )) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - outfile.write(' state=%s' % (self.gds_format_string(quote_attrib(self.state).encode(ExternalEncoding), input_name='state'), )) - def exportChildren(self, outfile, level, namespace_='', name_='RNAObs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(RNAObs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNAObs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - showIndent(outfile, level) - outfile.write('char = "%s",\n' % (self.char,)) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - showIndent(outfile, level) - outfile.write('state = "%s",\n' % (self.state,)) - super(RNAObs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNAObs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('char', node) - if value is not None and 'char' not in already_processed: - already_processed.append('char') - self.char = value - value = find_attr_value_('state', node) - if value is not None and 'state' not in already_processed: - already_processed.append('state') - self.state = value - super(RNAObs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class RNAObs - - -class RestrictionObs(AbstractObs): - """This is a single cell in a matrix containing a restriction site - observation.""" - subclass = None - superclass = AbstractObs - def __init__(self, about=None, meta=None, label=None, char=None, state=None, valueOf_=None): - super(RestrictionObs, self).__init__(about, meta, label, char, state, ) - self.char = _cast(None, char) - self.state = _cast(None, state) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if RestrictionObs.subclass: - return RestrictionObs.subclass(*args_, **kwargs_) - else: - return RestrictionObs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def get_state(self): return self.state - def set_state(self, state): self.state = state - def export(self, outfile, level, namespace_='', name_='RestrictionObs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionObs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RestrictionObs'): - super(RestrictionObs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionObs') - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - outfile.write(' char=%s' % (self.gds_format_string(quote_attrib(self.char).encode(ExternalEncoding), input_name='char'), )) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - outfile.write(' state=%s' % (self.gds_format_string(quote_attrib(self.state).encode(ExternalEncoding), input_name='state'), )) - def exportChildren(self, outfile, level, namespace_='', name_='RestrictionObs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(RestrictionObs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RestrictionObs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - showIndent(outfile, level) - outfile.write('char = "%s",\n' % (self.char,)) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - showIndent(outfile, level) - outfile.write('state = "%s",\n' % (self.state,)) - super(RestrictionObs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RestrictionObs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('char', node) - if value is not None and 'char' not in already_processed: - already_processed.append('char') - self.char = value - value = find_attr_value_('state', node) - if value is not None and 'state' not in already_processed: - already_processed.append('state') - self.state = value - super(RestrictionObs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class RestrictionObs - - -class AAObs(AbstractObs): - """This is a single cell in a matrix containing an amino acid - observation.""" - subclass = None - superclass = AbstractObs - def __init__(self, about=None, meta=None, label=None, char=None, state=None, valueOf_=None): - super(AAObs, self).__init__(about, meta, label, char, state, ) - self.char = _cast(None, char) - self.state = _cast(None, state) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if AAObs.subclass: - return AAObs.subclass(*args_, **kwargs_) - else: - return AAObs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def get_state(self): return self.state - def set_state(self, state): self.state = state - def export(self, outfile, level, namespace_='', name_='AAObs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AAObs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AAObs'): - super(AAObs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AAObs') - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - outfile.write(' char=%s' % (self.gds_format_string(quote_attrib(self.char).encode(ExternalEncoding), input_name='char'), )) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - outfile.write(' state=%s' % (self.gds_format_string(quote_attrib(self.state).encode(ExternalEncoding), input_name='state'), )) - def exportChildren(self, outfile, level, namespace_='', name_='AAObs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(AAObs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AAObs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - showIndent(outfile, level) - outfile.write('char = "%s",\n' % (self.char,)) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - showIndent(outfile, level) - outfile.write('state = "%s",\n' % (self.state,)) - super(AAObs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AAObs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('char', node) - if value is not None and 'char' not in already_processed: - already_processed.append('char') - self.char = value - value = find_attr_value_('state', node) - if value is not None and 'state' not in already_processed: - already_processed.append('state') - self.state = value - super(AAObs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class AAObs - - -class DNAObs(AbstractObs): - """This is a single cell in a matrix containing a nucleotide - observation.""" - subclass = None - superclass = AbstractObs - def __init__(self, about=None, meta=None, label=None, char=None, state=None, valueOf_=None): - super(DNAObs, self).__init__(about, meta, label, char, state, ) - self.char = _cast(None, char) - self.state = _cast(None, state) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if DNAObs.subclass: - return DNAObs.subclass(*args_, **kwargs_) - else: - return DNAObs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_char(self): return self.char - def set_char(self, char): self.char = char - def get_state(self): return self.state - def set_state(self, state): self.state = state - def export(self, outfile, level, namespace_='', name_='DNAObs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNAObs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNAObs'): - super(DNAObs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNAObs') - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - outfile.write(' char=%s' % (self.gds_format_string(quote_attrib(self.char).encode(ExternalEncoding), input_name='char'), )) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - outfile.write(' state=%s' % (self.gds_format_string(quote_attrib(self.state).encode(ExternalEncoding), input_name='state'), )) - def exportChildren(self, outfile, level, namespace_='', name_='DNAObs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(DNAObs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNAObs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - showIndent(outfile, level) - outfile.write('char = "%s",\n' % (self.char,)) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - showIndent(outfile, level) - outfile.write('state = "%s",\n' % (self.state,)) - super(DNAObs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNAObs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('char', node) - if value is not None and 'char' not in already_processed: - already_processed.append('char') - self.char = value - value = find_attr_value_('state', node) - if value is not None and 'state' not in already_processed: - already_processed.append('state') - self.state = value - super(DNAObs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class DNAObs - - -class AbstractChar(IDTagged): - """The AbstractChar type is the superclass for a column definition, - which may have a "states" attribute that refers to an - AbstractStates element, a codon attribute of type CodonPosition - and an id attribute that may be an actual id (e.g. for - categorical matrices where observations explicitly refer to a - column definition) or an integer for sequence matrices.""" - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, tokens=None, states=None, codon=None, valueOf_=None): - super(AbstractChar, self).__init__(about, meta, label, id, ) - self.tokens = _cast(None, tokens) - self.states = _cast(None, states) - self.codon = _cast(None, codon) - pass - def factory(*args_, **kwargs_): - if AbstractChar.subclass: - return AbstractChar.subclass(*args_, **kwargs_) - else: - return AbstractChar(*args_, **kwargs_) - factory = staticmethod(factory) - def get_tokens(self): return self.tokens - def set_tokens(self, tokens): self.tokens = tokens - def validate_MSTokenLength(self, value): - # Validate type MSTokenLength, a restriction on xs:positiveInteger. - pass - def get_states(self): return self.states - def set_states(self, states): self.states = states - def get_codon(self): return self.codon - def set_codon(self, codon): self.codon = codon - def validate_CodonPosition(self, value): - # Validate type CodonPosition, a restriction on xs:nonNegativeInteger. - pass - def export(self, outfile, level, namespace_='', name_='AbstractChar', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractChar') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractChar"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractChar'): - super(AbstractChar, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractChar') - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - outfile.write(' tokens=%s' % (quote_attrib(self.tokens), )) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - outfile.write(' states=%s' % (self.gds_format_string(quote_attrib(self.states).encode(ExternalEncoding), input_name='states'), )) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - outfile.write(' codon=%s' % (quote_attrib(self.codon), )) - def exportChildren(self, outfile, level, namespace_='', name_='AbstractChar', fromsubclass_=False): - super(AbstractChar, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(AbstractChar, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractChar'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - showIndent(outfile, level) - outfile.write('tokens = %d,\n' % (self.tokens,)) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - showIndent(outfile, level) - outfile.write('states = "%s",\n' % (self.states,)) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - showIndent(outfile, level) - outfile.write('codon = %d,\n' % (self.codon,)) - super(AbstractChar, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractChar, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('tokens', node) - if value is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - try: - self.tokens = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.tokens <= 0: - raise_parse_error(node, 'Invalid PositiveInteger') - self.validate_MSTokenLength(self.tokens) # validate type MSTokenLength - value = find_attr_value_('states', node) - if value is not None and 'states' not in already_processed: - already_processed.append('states') - self.states = value - value = find_attr_value_('codon', node) - if value is not None and 'codon' not in already_processed: - already_processed.append('codon') - try: - self.codon = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.codon < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - self.validate_CodonPosition(self.codon) # validate type CodonPosition - super(AbstractChar, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(AbstractChar, self).buildChildren(child_, node, nodeName_, True) - pass -# end class AbstractChar - - -class AbstractStates(IDTagged): - """A container for a set of AbstractState elements.""" - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, state=None, polymorphic_state_set=None, uncertain_state_set=None, set=None, valueOf_=None): - super(AbstractStates, self).__init__(about, meta, label, id, ) - if state is None: - self.state = [] - else: - self.state = state - if polymorphic_state_set is None: - self.polymorphic_state_set = [] - else: - self.polymorphic_state_set = polymorphic_state_set - if uncertain_state_set is None: - self.uncertain_state_set = [] - else: - self.uncertain_state_set = uncertain_state_set - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AbstractStates.subclass: - return AbstractStates.subclass(*args_, **kwargs_) - else: - return AbstractStates(*args_, **kwargs_) - factory = staticmethod(factory) - def get_state(self): return self.state - def set_state(self, state): self.state = state - def add_state(self, value): self.state.append(value) - def insert_state(self, index, value): self.state[index] = value - def get_polymorphic_state_set(self): return self.polymorphic_state_set - def set_polymorphic_state_set(self, polymorphic_state_set): self.polymorphic_state_set = polymorphic_state_set - def add_polymorphic_state_set(self, value): self.polymorphic_state_set.append(value) - def insert_polymorphic_state_set(self, index, value): self.polymorphic_state_set[index] = value - def get_uncertain_state_set(self): return self.uncertain_state_set - def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set - def add_uncertain_state_set(self, value): self.uncertain_state_set.append(value) - def insert_uncertain_state_set(self, index, value): self.uncertain_state_set[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AbstractStates', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractStates') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractStates"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractStates'): - super(AbstractStates, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractStates') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractStates', fromsubclass_=False): - super(AbstractStates, self).exportChildren(outfile, level, namespace_, name_, True) - for state_ in self.get_state(): - state_.export(outfile, level, namespace_, name_='state') - for polymorphic_state_set_ in self.get_polymorphic_state_set(): - polymorphic_state_set_.export(outfile, level, namespace_, name_='polymorphic_state_set') - for uncertain_state_set_ in self.get_uncertain_state_set(): - uncertain_state_set_.export(outfile, level, namespace_, name_='uncertain_state_set') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.state or - self.polymorphic_state_set or - self.uncertain_state_set or - self.set or - super(AbstractStates, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractStates'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractStates, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractStates, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('state=[\n') - level += 1 - for state_ in self.state: - showIndent(outfile, level) - outfile.write('model_.AbstractState(\n') - state_.exportLiteral(outfile, level, name_='AbstractState') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('polymorphic_state_set=[\n') - level += 1 - for polymorphic_state_set_ in self.polymorphic_state_set: - showIndent(outfile, level) - outfile.write('model_.AbstractPolymorphicStateSet(\n') - polymorphic_state_set_.exportLiteral(outfile, level, name_='AbstractPolymorphicStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('uncertain_state_set=[\n') - level += 1 - for uncertain_state_set_ in self.uncertain_state_set: - showIndent(outfile, level) - outfile.write('model_.AbstractUncertainStateSet(\n') - uncertain_state_set_.exportLiteral(outfile, level, name_='AbstractUncertainStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.StateSet(\n') - set_.exportLiteral(outfile, level, name_='StateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractStates, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'state': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.state.append(obj_) - elif nodeName_ == 'polymorphic_state_set': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.polymorphic_state_set.append(obj_) - elif nodeName_ == 'uncertain_state_set': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.uncertain_state_set.append(obj_) - elif nodeName_ == 'set': - obj_ = StateSet.factory() - obj_.build(child_) - self.set.append(obj_) - super(AbstractStates, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractStates - - -class AbstractState(IDTagged): - """The AbstractState type is the super-class for a state definition. - The element has a required symbol attribute that in restricted - concrete subclasses must be of a sensible type such as a single - IUPAC character. It may enclose zero or more AbstractMapping - elements to resolve ambiguities.""" - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, valueOf_=None): - super(AbstractState, self).__init__(about, meta, label, id, ) - self.symbol = _cast(None, symbol) - pass - def factory(*args_, **kwargs_): - if AbstractState.subclass: - return AbstractState.subclass(*args_, **kwargs_) - else: - return AbstractState(*args_, **kwargs_) - factory = staticmethod(factory) - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def export(self, outfile, level, namespace_='', name_='AbstractState', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractState') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractState"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractState'): - super(AbstractState, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractState') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='AbstractState', fromsubclass_=False): - super(AbstractState, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(AbstractState, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractState'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = %s,\n' % (self.symbol,)) - super(AbstractState, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractState, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - self.symbol = value - super(AbstractState, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(AbstractState, self).buildChildren(child_, node, nodeName_, True) - pass -# end class AbstractState - - -class ContinuousChar(AbstractChar): - """A concrete implementation of the char element, which requires only - an id attribute.""" - subclass = None - superclass = AbstractChar - def __init__(self, about=None, meta=None, label=None, id=None, tokens=None, states=None, codon=None, valueOf_=None): - super(ContinuousChar, self).__init__(about, meta, label, id, tokens, states, codon, ) - self.states = _cast(None, states) - self.tokens = _cast(None, tokens) - self.codon = _cast(None, codon) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if ContinuousChar.subclass: - return ContinuousChar.subclass(*args_, **kwargs_) - else: - return ContinuousChar(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_states(self): return self.states - def set_states(self, states): self.states = states - def get_tokens(self): return self.tokens - def set_tokens(self, tokens): self.tokens = tokens - def validate_MSTokenLength(self, value): - # Validate type MSTokenLength, a restriction on xs:positiveInteger. - pass - def get_codon(self): return self.codon - def set_codon(self, codon): self.codon = codon - def validate_CodonPosition(self, value): - # Validate type CodonPosition, a restriction on xs:nonNegativeInteger. - pass - def export(self, outfile, level, namespace_='', name_='ContinuousChar', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousChar') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ContinuousChar'): - super(ContinuousChar, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousChar') - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - outfile.write(' states=%s' % (self.gds_format_string(quote_attrib(self.states).encode(ExternalEncoding), input_name='states'), )) - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - outfile.write(' tokens=%s' % (quote_attrib(self.tokens), )) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - outfile.write(' codon=%s' % (quote_attrib(self.codon), )) - def exportChildren(self, outfile, level, namespace_='', name_='ContinuousChar', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(ContinuousChar, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ContinuousChar'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - showIndent(outfile, level) - outfile.write('states = "%s",\n' % (self.states,)) - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - showIndent(outfile, level) - outfile.write('tokens = %d,\n' % (self.tokens,)) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - showIndent(outfile, level) - outfile.write('codon = %d,\n' % (self.codon,)) - super(ContinuousChar, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ContinuousChar, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('states', node) - if value is not None and 'states' not in already_processed: - already_processed.append('states') - self.states = value - value = find_attr_value_('tokens', node) - if value is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - try: - self.tokens = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.tokens <= 0: - raise_parse_error(node, 'Invalid PositiveInteger') - self.validate_MSTokenLength(self.tokens) # validate type MSTokenLength - value = find_attr_value_('codon', node) - if value is not None and 'codon' not in already_processed: - already_processed.append('codon') - try: - self.codon = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.codon < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - self.validate_CodonPosition(self.codon) # validate type CodonPosition - super(ContinuousChar, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class ContinuousChar - - -class AbstractSet(IDTagged): - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, valueOf_=None): - super(AbstractSet, self).__init__(about, meta, label, id, ) - pass - def factory(*args_, **kwargs_): - if AbstractSet.subclass: - return AbstractSet.subclass(*args_, **kwargs_) - else: - return AbstractSet(*args_, **kwargs_) - factory = staticmethod(factory) - def export(self, outfile, level, namespace_='', name_='AbstractSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractSet') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractSet"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractSet'): - super(AbstractSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractSet') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractSet', fromsubclass_=False): - super(AbstractSet, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(AbstractSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractSet, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(AbstractSet, self).buildChildren(child_, node, nodeName_, True) - pass -# end class AbstractSet - - -class TaxaLinked(IDTagged): - """The TaxaLinked complexType is a super class for objects that that - require an otus id reference.""" - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, valueOf_=None): - super(TaxaLinked, self).__init__(about, meta, label, id, ) - self.otus = _cast(None, otus) - pass - def factory(*args_, **kwargs_): - if TaxaLinked.subclass: - return TaxaLinked.subclass(*args_, **kwargs_) - else: - return TaxaLinked(*args_, **kwargs_) - factory = staticmethod(factory) - def get_otus(self): return self.otus - def set_otus(self, otus): self.otus = otus - def export(self, outfile, level, namespace_='', name_='TaxaLinked', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='TaxaLinked') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="TaxaLinked"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='TaxaLinked'): - super(TaxaLinked, self).exportAttributes(outfile, level, already_processed, namespace_, name_='TaxaLinked') - if self.otus is not None and 'otus' not in already_processed: - already_processed.append('otus') - outfile.write(' otus=%s' % (self.gds_format_string(quote_attrib(self.otus).encode(ExternalEncoding), input_name='otus'), )) - def exportChildren(self, outfile, level, namespace_='', name_='TaxaLinked', fromsubclass_=False): - super(TaxaLinked, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(TaxaLinked, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='TaxaLinked'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.otus is not None and 'otus' not in already_processed: - already_processed.append('otus') - showIndent(outfile, level) - outfile.write('otus = "%s",\n' % (self.otus,)) - super(TaxaLinked, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(TaxaLinked, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('otus', node) - if value is not None and 'otus' not in already_processed: - already_processed.append('otus') - self.otus = value - super(TaxaLinked, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(TaxaLinked, self).buildChildren(child_, node, nodeName_, True) - pass -# end class TaxaLinked - - -class OptionalTaxonLinked(IDTagged): - """The OptionalOTULinked complexType is a super class for objects that - that optionally have an otu id reference.""" - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, valueOf_=None): - super(OptionalTaxonLinked, self).__init__(about, meta, label, id, ) - self.otu = _cast(None, otu) - pass - def factory(*args_, **kwargs_): - if OptionalTaxonLinked.subclass: - return OptionalTaxonLinked.subclass(*args_, **kwargs_) - else: - return OptionalTaxonLinked(*args_, **kwargs_) - factory = staticmethod(factory) - def get_otu(self): return self.otu - def set_otu(self, otu): self.otu = otu - def export(self, outfile, level, namespace_='', name_='OptionalTaxonLinked', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='OptionalTaxonLinked') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="OptionalTaxonLinked"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='OptionalTaxonLinked'): - super(OptionalTaxonLinked, self).exportAttributes(outfile, level, already_processed, namespace_, name_='OptionalTaxonLinked') - if self.otu is not None and 'otu' not in already_processed: - already_processed.append('otu') - outfile.write(' otu=%s' % (self.gds_format_string(quote_attrib(self.otu).encode(ExternalEncoding), input_name='otu'), )) - def exportChildren(self, outfile, level, namespace_='', name_='OptionalTaxonLinked', fromsubclass_=False): - super(OptionalTaxonLinked, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(OptionalTaxonLinked, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='OptionalTaxonLinked'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.otu is not None and 'otu' not in already_processed: - already_processed.append('otu') - showIndent(outfile, level) - outfile.write('otu = "%s",\n' % (self.otu,)) - super(OptionalTaxonLinked, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(OptionalTaxonLinked, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('otu', node) - if value is not None and 'otu' not in already_processed: - already_processed.append('otu') - self.otu = value - super(OptionalTaxonLinked, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(OptionalTaxonLinked, self).buildChildren(child_, node, nodeName_, True) - pass -# end class OptionalTaxonLinked - - -class TaxonLinked(IDTagged): - """The TaxonLinked complexType is a super class for objects that - require a taxon id reference.""" - subclass = None - superclass = IDTagged - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, valueOf_=None): - super(TaxonLinked, self).__init__(about, meta, label, id, ) - self.otu = _cast(None, otu) - pass - def factory(*args_, **kwargs_): - if TaxonLinked.subclass: - return TaxonLinked.subclass(*args_, **kwargs_) - else: - return TaxonLinked(*args_, **kwargs_) - factory = staticmethod(factory) - def get_otu(self): return self.otu - def set_otu(self, otu): self.otu = otu - def export(self, outfile, level, namespace_='', name_='TaxonLinked', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='TaxonLinked') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="TaxonLinked"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='TaxonLinked'): - super(TaxonLinked, self).exportAttributes(outfile, level, already_processed, namespace_, name_='TaxonLinked') - if self.otu is not None and 'otu' not in already_processed: - already_processed.append('otu') - outfile.write(' otu=%s' % (self.gds_format_string(quote_attrib(self.otu).encode(ExternalEncoding), input_name='otu'), )) - def exportChildren(self, outfile, level, namespace_='', name_='TaxonLinked', fromsubclass_=False): - super(TaxonLinked, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(TaxonLinked, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='TaxonLinked'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.otu is not None and 'otu' not in already_processed: - already_processed.append('otu') - showIndent(outfile, level) - outfile.write('otu = "%s",\n' % (self.otu,)) - super(TaxonLinked, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(TaxonLinked, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('otu', node) - if value is not None and 'otu' not in already_processed: - already_processed.append('otu') - self.otu = value - super(TaxonLinked, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(TaxonLinked, self).buildChildren(child_, node, nodeName_, True) - pass -# end class TaxonLinked - - -class IntNetwork(AbstractNetwork): - """A concrete network implementation, with integer edge lengths.""" - subclass = None - superclass = AbstractNetwork - def __init__(self, about=None, meta=None, label=None, id=None, node=None, edge=None, set=None, valueOf_=None): - super(IntNetwork, self).__init__(about, meta, label, id, node, edge, set, ) - if node is None: - self.node = [] - else: - self.node = node - if edge is None: - self.edge = [] - else: - self.edge = edge - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if IntNetwork.subclass: - return IntNetwork.subclass(*args_, **kwargs_) - else: - return IntNetwork(*args_, **kwargs_) - factory = staticmethod(factory) - def get_node(self): return self.node - def set_node(self, node): self.node = node - def add_node(self, value): self.node.append(value) - def insert_node(self, index, value): self.node[index] = value - def get_edge(self): return self.edge - def set_edge(self, edge): self.edge = edge - def add_edge(self, value): self.edge.append(value) - def insert_edge(self, index, value): self.edge[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='IntNetwork', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='IntNetwork') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='IntNetwork'): - super(IntNetwork, self).exportAttributes(outfile, level, already_processed, namespace_, name_='IntNetwork') - def exportChildren(self, outfile, level, namespace_='', name_='IntNetwork', fromsubclass_=False): - for node_ in self.node: - node_.export(outfile, level, namespace_, name_='node') - for edge_ in self.edge: - edge_.export(outfile, level, namespace_, name_='edge') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.node or - self.edge or - self.set or - super(IntNetwork, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='IntNetwork'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(IntNetwork, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(IntNetwork, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('node=[\n') - level += 1 - for node_ in self.node: - showIndent(outfile, level) - outfile.write('model_.NetworkNode(\n') - node_.exportLiteral(outfile, level, name_='NetworkNode') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('edge=[\n') - level += 1 - for edge_ in self.edge: - showIndent(outfile, level) - outfile.write('model_.NetworkIntEdge(\n') - edge_.exportLiteral(outfile, level, name_='NetworkIntEdge') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.NodeAndRootEdgeAndEdgeSet(\n') - set_.exportLiteral(outfile, level, name_='NodeAndRootEdgeAndEdgeSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(IntNetwork, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'node': - obj_ = NetworkNode.factory() - obj_.build(child_) - self.node.append(obj_) - elif nodeName_ == 'edge': - obj_ = NetworkIntEdge.factory() - obj_.build(child_) - self.edge.append(obj_) - elif nodeName_ == 'set': - obj_ = NodeAndRootEdgeAndEdgeSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class IntNetwork - - -class FloatNetwork(AbstractNetwork): - """A concrete network implementation, with floating point edge lengths.""" - subclass = None - superclass = AbstractNetwork - def __init__(self, about=None, meta=None, label=None, id=None, node=None, edge=None, set=None, valueOf_=None): - super(FloatNetwork, self).__init__(about, meta, label, id, node, edge, set, ) - if node is None: - self.node = [] - else: - self.node = node - if edge is None: - self.edge = [] - else: - self.edge = edge - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if FloatNetwork.subclass: - return FloatNetwork.subclass(*args_, **kwargs_) - else: - return FloatNetwork(*args_, **kwargs_) - factory = staticmethod(factory) - def get_node(self): return self.node - def set_node(self, node): self.node = node - def add_node(self, value): self.node.append(value) - def insert_node(self, index, value): self.node[index] = value - def get_edge(self): return self.edge - def set_edge(self, edge): self.edge = edge - def add_edge(self, value): self.edge.append(value) - def insert_edge(self, index, value): self.edge[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='FloatNetwork', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='FloatNetwork') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='FloatNetwork'): - super(FloatNetwork, self).exportAttributes(outfile, level, already_processed, namespace_, name_='FloatNetwork') - def exportChildren(self, outfile, level, namespace_='', name_='FloatNetwork', fromsubclass_=False): - for node_ in self.node: - node_.export(outfile, level, namespace_, name_='node') - for edge_ in self.edge: - edge_.export(outfile, level, namespace_, name_='edge') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.node or - self.edge or - self.set or - super(FloatNetwork, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='FloatNetwork'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(FloatNetwork, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(FloatNetwork, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('node=[\n') - level += 1 - for node_ in self.node: - showIndent(outfile, level) - outfile.write('model_.NetworkNode(\n') - node_.exportLiteral(outfile, level, name_='NetworkNode') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('edge=[\n') - level += 1 - for edge_ in self.edge: - showIndent(outfile, level) - outfile.write('model_.NetworkFloatEdge(\n') - edge_.exportLiteral(outfile, level, name_='NetworkFloatEdge') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.NodeAndRootEdgeAndEdgeSet(\n') - set_.exportLiteral(outfile, level, name_='NodeAndRootEdgeAndEdgeSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(FloatNetwork, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'node': - obj_ = NetworkNode.factory() - obj_.build(child_) - self.node.append(obj_) - elif nodeName_ == 'edge': - obj_ = NetworkFloatEdge.factory() - obj_.build(child_) - self.edge.append(obj_) - elif nodeName_ == 'set': - obj_ = NodeAndRootEdgeAndEdgeSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class FloatNetwork - - -class NetworkIntEdge(AbstractEdge): - """A concrete network edge implementation, with int edge.""" - subclass = None - superclass = AbstractEdge - def __init__(self, about=None, meta=None, label=None, id=None, source=None, length=None, target=None, valueOf_=None): - super(NetworkIntEdge, self).__init__(about, meta, label, id, source, length, target, ) - self.length = _cast(int, length) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if NetworkIntEdge.subclass: - return NetworkIntEdge.subclass(*args_, **kwargs_) - else: - return NetworkIntEdge(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_length(self): return self.length - def set_length(self, length): self.length = length - def export(self, outfile, level, namespace_='', name_='NetworkIntEdge', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='NetworkIntEdge') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='NetworkIntEdge'): - super(NetworkIntEdge, self).exportAttributes(outfile, level, already_processed, namespace_, name_='NetworkIntEdge') - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - outfile.write(' length="%s"' % self.gds_format_integer(self.length, input_name='length')) - def exportChildren(self, outfile, level, namespace_='', name_='NetworkIntEdge', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(NetworkIntEdge, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='NetworkIntEdge'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - showIndent(outfile, level) - outfile.write('length = %d,\n' % (self.length,)) - super(NetworkIntEdge, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(NetworkIntEdge, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('length', node) - if value is not None and 'length' not in already_processed: - already_processed.append('length') - try: - self.length = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - super(NetworkIntEdge, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class NetworkIntEdge - - -class NetworkFloatEdge(AbstractEdge): - """A concrete network edge implementation, with float edge.""" - subclass = None - superclass = AbstractEdge - def __init__(self, about=None, meta=None, label=None, id=None, source=None, length=None, target=None, valueOf_=None): - super(NetworkFloatEdge, self).__init__(about, meta, label, id, source, length, target, ) - self.length = _cast(float, length) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if NetworkFloatEdge.subclass: - return NetworkFloatEdge.subclass(*args_, **kwargs_) - else: - return NetworkFloatEdge(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_length(self): return self.length - def set_length(self, length): self.length = length - def export(self, outfile, level, namespace_='', name_='NetworkFloatEdge', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='NetworkFloatEdge') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='NetworkFloatEdge'): - super(NetworkFloatEdge, self).exportAttributes(outfile, level, already_processed, namespace_, name_='NetworkFloatEdge') - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - outfile.write(' length="%s"' % self.gds_format_double(self.length, input_name='length')) - def exportChildren(self, outfile, level, namespace_='', name_='NetworkFloatEdge', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(NetworkFloatEdge, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='NetworkFloatEdge'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - showIndent(outfile, level) - outfile.write('length = %e,\n' % (self.length,)) - super(NetworkFloatEdge, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(NetworkFloatEdge, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('length', node) - if value is not None and 'length' not in already_processed: - already_processed.append('length') - try: - self.length = float(value) - except ValueError, exp: - raise ValueError('Bad float/double attribute (length): %s' % exp) - super(NetworkFloatEdge, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class NetworkFloatEdge - - -class AbstractNode(OptionalTaxonLinked): - """The AbstractNode superclass is what concrete nodes inherit from by - restriction. It represents a node element much like that of - GraphML, i.e. an element that is connected into a tree by edge - elements.""" - subclass = None - superclass = OptionalTaxonLinked - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, root=False, valueOf_=None): - super(AbstractNode, self).__init__(about, meta, label, id, otu, ) - self.root = _cast(bool, root) - pass - def factory(*args_, **kwargs_): - if AbstractNode.subclass: - return AbstractNode.subclass(*args_, **kwargs_) - else: - return AbstractNode(*args_, **kwargs_) - factory = staticmethod(factory) - def get_root(self): return self.root - def set_root(self, root): self.root = root - def export(self, outfile, level, namespace_='', name_='AbstractNode', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractNode') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractNode"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractNode'): - super(AbstractNode, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractNode') - if self.root is not None and 'root' not in already_processed: - already_processed.append('root') - outfile.write(' root="%s"' % self.gds_format_boolean(self.gds_str_lower(str(self.root)), input_name='root')) - def exportChildren(self, outfile, level, namespace_='', name_='AbstractNode', fromsubclass_=False): - super(AbstractNode, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(AbstractNode, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractNode'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.root is not None and 'root' not in already_processed: - already_processed.append('root') - showIndent(outfile, level) - outfile.write('root = %s,\n' % (self.root,)) - super(AbstractNode, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractNode, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('root', node) - if value is not None and 'root' not in already_processed: - already_processed.append('root') - if value in ('true', '1'): - self.root = True - elif value in ('false', '0'): - self.root = False - else: - raise_parse_error(node, 'Bad boolean attribute') - super(AbstractNode, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(AbstractNode, self).buildChildren(child_, node, nodeName_, True) - pass -# end class AbstractNode - - -class TreeNode(AbstractNode): - """A concrete node implementation.""" - subclass = None - superclass = AbstractNode - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, root=False, valueOf_=None): - super(TreeNode, self).__init__(about, meta, label, id, otu, root, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if TreeNode.subclass: - return TreeNode.subclass(*args_, **kwargs_) - else: - return TreeNode(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def export(self, outfile, level, namespace_='', name_='TreeNode', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='TreeNode') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='TreeNode'): - super(TreeNode, self).exportAttributes(outfile, level, already_processed, namespace_, name_='TreeNode') - def exportChildren(self, outfile, level, namespace_='', name_='TreeNode', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(TreeNode, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='TreeNode'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(TreeNode, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(TreeNode, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(TreeNode, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class TreeNode - - -class Trees(TaxaLinked): - """A concrete container for tree objects.""" - subclass = None - superclass = TaxaLinked - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, network=None, tree=None, set=None, valueOf_=None): - super(Trees, self).__init__(about, meta, label, id, otus, ) - if network is None: - self.network = [] - else: - self.network = network - if tree is None: - self.tree = [] - else: - self.tree = tree - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if Trees.subclass: - return Trees.subclass(*args_, **kwargs_) - else: - return Trees(*args_, **kwargs_) - factory = staticmethod(factory) - def get_network(self): return self.network - def set_network(self, network): self.network = network - def add_network(self, value): self.network.append(value) - def insert_network(self, index, value): self.network[index] = value - def get_tree(self): return self.tree - def set_tree(self, tree): self.tree = tree - def add_tree(self, value): self.tree.append(value) - def insert_tree(self, index, value): self.tree[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='Trees', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Trees') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="Trees"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='Trees'): - super(Trees, self).exportAttributes(outfile, level, already_processed, namespace_, name_='Trees') - def exportChildren(self, outfile, level, namespace_='', name_='Trees', fromsubclass_=False): - super(Trees, self).exportChildren(outfile, level, namespace_, name_, True) - for network_ in self.get_network(): - network_.export(outfile, level, namespace_, name_='network') - for tree_ in self.get_tree(): - tree_.export(outfile, level, namespace_, name_='tree') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.network or - self.tree or - self.set or - super(Trees, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Trees'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(Trees, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(Trees, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('network=[\n') - level += 1 - for network_ in self.network: - showIndent(outfile, level) - outfile.write('model_.AbstractNetwork(\n') - network_.exportLiteral(outfile, level, name_='AbstractNetwork') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('tree=[\n') - level += 1 - for tree_ in self.tree: - showIndent(outfile, level) - outfile.write('model_.AbstractTree(\n') - tree_.exportLiteral(outfile, level, name_='AbstractTree') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.TreeAndNetworkSet(\n') - set_.exportLiteral(outfile, level, name_='TreeAndNetworkSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(Trees, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'network': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.network.append(obj_) - elif nodeName_ == 'tree': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.tree.append(obj_) - elif nodeName_ == 'set': - obj_ = TreeAndNetworkSet.factory() - obj_.build(child_) - self.set.append(obj_) - super(Trees, self).buildChildren(child_, node, nodeName_, True) -# end class Trees - - -class StandardChar(AbstractChar): - """A concrete implementation of the char element, which requires a - states attribute to refer to a set of defined states""" - subclass = None - superclass = AbstractChar - def __init__(self, about=None, meta=None, label=None, id=None, tokens=None, states=None, codon=None, valueOf_=None): - super(StandardChar, self).__init__(about, meta, label, id, tokens, states, codon, ) - self.tokens = _cast(None, tokens) - self.states = _cast(None, states) - self.codon = _cast(None, codon) - self.id = _cast(None, id) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if StandardChar.subclass: - return StandardChar.subclass(*args_, **kwargs_) - else: - return StandardChar(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_tokens(self): return self.tokens - def set_tokens(self, tokens): self.tokens = tokens - def validate_MSTokenLength(self, value): - # Validate type MSTokenLength, a restriction on xs:positiveInteger. - pass - def get_states(self): return self.states - def set_states(self, states): self.states = states - def get_codon(self): return self.codon - def set_codon(self, codon): self.codon = codon - def validate_CodonPosition(self, value): - # Validate type CodonPosition, a restriction on xs:nonNegativeInteger. - pass - def get_id(self): return self.id - def set_id(self, id): self.id = id - def export(self, outfile, level, namespace_='', name_='StandardChar', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardChar') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardChar'): - super(StandardChar, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardChar') - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - outfile.write(' tokens=%s' % (quote_attrib(self.tokens), )) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - outfile.write(' states=%s' % (self.gds_format_string(quote_attrib(self.states).encode(ExternalEncoding), input_name='states'), )) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - outfile.write(' codon=%s' % (quote_attrib(self.codon), )) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) - def exportChildren(self, outfile, level, namespace_='', name_='StandardChar', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(StandardChar, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardChar'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - showIndent(outfile, level) - outfile.write('tokens = %d,\n' % (self.tokens,)) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - showIndent(outfile, level) - outfile.write('states = "%s",\n' % (self.states,)) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - showIndent(outfile, level) - outfile.write('codon = %d,\n' % (self.codon,)) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = "%s",\n' % (self.id,)) - super(StandardChar, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardChar, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('tokens', node) - if value is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - try: - self.tokens = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.tokens <= 0: - raise_parse_error(node, 'Invalid PositiveInteger') - self.validate_MSTokenLength(self.tokens) # validate type MSTokenLength - value = find_attr_value_('states', node) - if value is not None and 'states' not in already_processed: - already_processed.append('states') - self.states = value - value = find_attr_value_('codon', node) - if value is not None and 'codon' not in already_processed: - already_processed.append('codon') - try: - self.codon = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.codon < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - self.validate_CodonPosition(self.codon) # validate type CodonPosition - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - self.id = value - super(StandardChar, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class StandardChar - - -class StandardStates(AbstractStates): - """A container for a set of states.""" - subclass = None - superclass = AbstractStates - def __init__(self, about=None, meta=None, label=None, id=None, state=None, polymorphic_state_set=None, uncertain_state_set=None, set=None, valueOf_=None): - super(StandardStates, self).__init__(about, meta, label, id, state, polymorphic_state_set, uncertain_state_set, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if state is None: - self.state = [] - else: - self.state = state - if polymorphic_state_set is None: - self.polymorphic_state_set = [] - else: - self.polymorphic_state_set = polymorphic_state_set - if uncertain_state_set is None: - self.uncertain_state_set = [] - else: - self.uncertain_state_set = uncertain_state_set - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if StandardStates.subclass: - return StandardStates.subclass(*args_, **kwargs_) - else: - return StandardStates(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_state(self): return self.state - def set_state(self, state): self.state = state - def add_state(self, value): self.state.append(value) - def insert_state(self, index, value): self.state[index] = value - def get_polymorphic_state_set(self): return self.polymorphic_state_set - def set_polymorphic_state_set(self, polymorphic_state_set): self.polymorphic_state_set = polymorphic_state_set - def add_polymorphic_state_set(self, value): self.polymorphic_state_set.append(value) - def insert_polymorphic_state_set(self, index, value): self.polymorphic_state_set[index] = value - def get_uncertain_state_set(self): return self.uncertain_state_set - def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set - def add_uncertain_state_set(self, value): self.uncertain_state_set.append(value) - def insert_uncertain_state_set(self, index, value): self.uncertain_state_set[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='StandardStates', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardStates') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardStates'): - super(StandardStates, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardStates') - def exportChildren(self, outfile, level, namespace_='', name_='StandardStates', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for state_ in self.state: - state_.export(outfile, level, namespace_, name_='state') - for polymorphic_state_set_ in self.polymorphic_state_set: - polymorphic_state_set_.export(outfile, level, namespace_, name_='polymorphic_state_set') - for uncertain_state_set_ in self.uncertain_state_set: - uncertain_state_set_.export(outfile, level, namespace_, name_='uncertain_state_set') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.state or - self.polymorphic_state_set or - self.uncertain_state_set or - self.set or - super(StandardStates, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardStates'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(StandardStates, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardStates, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('state=[\n') - level += 1 - for state_ in self.state: - showIndent(outfile, level) - outfile.write('model_.StandardState(\n') - state_.exportLiteral(outfile, level, name_='StandardState') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('polymorphic_state_set=[\n') - level += 1 - for polymorphic_state_set_ in self.polymorphic_state_set: - showIndent(outfile, level) - outfile.write('model_.StandardPolymorphicStateSet(\n') - polymorphic_state_set_.exportLiteral(outfile, level, name_='StandardPolymorphicStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('uncertain_state_set=[\n') - level += 1 - for uncertain_state_set_ in self.uncertain_state_set: - showIndent(outfile, level) - outfile.write('model_.StandardUncertainStateSet(\n') - uncertain_state_set_.exportLiteral(outfile, level, name_='StandardUncertainStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.StateSet(\n') - set_.exportLiteral(outfile, level, name_='StateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(StandardStates, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'state': - obj_ = StandardState.factory() - obj_.build(child_) - self.state.append(obj_) - elif nodeName_ == 'polymorphic_state_set': - obj_ = StandardPolymorphicStateSet.factory() - obj_.build(child_) - self.polymorphic_state_set.append(obj_) - elif nodeName_ == 'uncertain_state_set': - obj_ = StandardUncertainStateSet.factory() - obj_.build(child_) - self.uncertain_state_set.append(obj_) - elif nodeName_ == 'set': - obj_ = StateSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class StandardStates - - -class StandardState(AbstractState): - """This is a concrete implementation of the state element, which - requires a symbol element, in this case restricted to integers, - and optional mapping elements to refer to other states.""" - subclass = None - superclass = AbstractState - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, valueOf_=None): - super(StandardState, self).__init__(about, meta, label, id, symbol, ) - self.symbol = _cast(None, symbol) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if StandardState.subclass: - return StandardState.subclass(*args_, **kwargs_) - else: - return StandardState(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_StandardToken(self, value): - # Validate type StandardToken, a restriction on xs:integer. - pass - def export(self, outfile, level, namespace_='', name_='StandardState', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardState') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardState'): - super(StandardState, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardState') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='StandardState', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(StandardState, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardState'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = %d,\n' % (self.symbol,)) - super(StandardState, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardState, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - try: - self.symbol = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - self.validate_StandardToken(self.symbol) # validate type StandardToken - super(StandardState, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class StandardState - - -class RNAChar(AbstractChar): - """A concrete implementation of the AbstractChar element, i.e. a single - column in an alignment.""" - subclass = None - superclass = AbstractChar - def __init__(self, about=None, meta=None, label=None, id=None, tokens=None, states=None, codon=None, valueOf_=None): - super(RNAChar, self).__init__(about, meta, label, id, tokens, states, codon, ) - self.tokens = _cast(None, tokens) - self.states = _cast(None, states) - self.codon = _cast(None, codon) - self.id = _cast(None, id) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if RNAChar.subclass: - return RNAChar.subclass(*args_, **kwargs_) - else: - return RNAChar(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_tokens(self): return self.tokens - def set_tokens(self, tokens): self.tokens = tokens - def validate_MSTokenLength(self, value): - # Validate type MSTokenLength, a restriction on xs:positiveInteger. - pass - def get_states(self): return self.states - def set_states(self, states): self.states = states - def get_codon(self): return self.codon - def set_codon(self, codon): self.codon = codon - def validate_CodonPosition(self, value): - # Validate type CodonPosition, a restriction on xs:nonNegativeInteger. - pass - def get_id(self): return self.id - def set_id(self, id): self.id = id - def export(self, outfile, level, namespace_='', name_='RNAChar', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNAChar') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNAChar'): - super(RNAChar, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNAChar') - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - outfile.write(' tokens=%s' % (quote_attrib(self.tokens), )) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - outfile.write(' states=%s' % (self.gds_format_string(quote_attrib(self.states).encode(ExternalEncoding), input_name='states'), )) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - outfile.write(' codon=%s' % (quote_attrib(self.codon), )) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) - def exportChildren(self, outfile, level, namespace_='', name_='RNAChar', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(RNAChar, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNAChar'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - showIndent(outfile, level) - outfile.write('tokens = %d,\n' % (self.tokens,)) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - showIndent(outfile, level) - outfile.write('states = "%s",\n' % (self.states,)) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - showIndent(outfile, level) - outfile.write('codon = %d,\n' % (self.codon,)) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = "%s",\n' % (self.id,)) - super(RNAChar, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNAChar, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('tokens', node) - if value is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - try: - self.tokens = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.tokens <= 0: - raise_parse_error(node, 'Invalid PositiveInteger') - self.validate_MSTokenLength(self.tokens) # validate type MSTokenLength - value = find_attr_value_('states', node) - if value is not None and 'states' not in already_processed: - already_processed.append('states') - self.states = value - value = find_attr_value_('codon', node) - if value is not None and 'codon' not in already_processed: - already_processed.append('codon') - try: - self.codon = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.codon < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - self.validate_CodonPosition(self.codon) # validate type CodonPosition - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - self.id = value - super(RNAChar, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class RNAChar - - -class RNAStates(AbstractStates): - """A container for a set of states.""" - subclass = None - superclass = AbstractStates - def __init__(self, about=None, meta=None, label=None, id=None, state=None, polymorphic_state_set=None, uncertain_state_set=None, set=None, valueOf_=None): - super(RNAStates, self).__init__(about, meta, label, id, state, polymorphic_state_set, uncertain_state_set, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if state is None: - self.state = [] - else: - self.state = state - if polymorphic_state_set is None: - self.polymorphic_state_set = [] - else: - self.polymorphic_state_set = polymorphic_state_set - if uncertain_state_set is None: - self.uncertain_state_set = [] - else: - self.uncertain_state_set = uncertain_state_set - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if RNAStates.subclass: - return RNAStates.subclass(*args_, **kwargs_) - else: - return RNAStates(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_state(self): return self.state - def set_state(self, state): self.state = state - def add_state(self, value): self.state.append(value) - def insert_state(self, index, value): self.state[index] = value - def get_polymorphic_state_set(self): return self.polymorphic_state_set - def set_polymorphic_state_set(self, polymorphic_state_set): self.polymorphic_state_set = polymorphic_state_set - def add_polymorphic_state_set(self, value): self.polymorphic_state_set.append(value) - def insert_polymorphic_state_set(self, index, value): self.polymorphic_state_set[index] = value - def get_uncertain_state_set(self): return self.uncertain_state_set - def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set - def add_uncertain_state_set(self, value): self.uncertain_state_set.append(value) - def insert_uncertain_state_set(self, index, value): self.uncertain_state_set[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='RNAStates', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNAStates') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNAStates'): - super(RNAStates, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNAStates') - def exportChildren(self, outfile, level, namespace_='', name_='RNAStates', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for state_ in self.state: - state_.export(outfile, level, namespace_, name_='state') - for polymorphic_state_set_ in self.polymorphic_state_set: - polymorphic_state_set_.export(outfile, level, namespace_, name_='polymorphic_state_set') - for uncertain_state_set_ in self.uncertain_state_set: - uncertain_state_set_.export(outfile, level, namespace_, name_='uncertain_state_set') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.state or - self.polymorphic_state_set or - self.uncertain_state_set or - self.set or - super(RNAStates, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNAStates'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RNAStates, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNAStates, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('state=[\n') - level += 1 - for state_ in self.state: - showIndent(outfile, level) - outfile.write('model_.RNAState(\n') - state_.exportLiteral(outfile, level, name_='RNAState') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('polymorphic_state_set=[\n') - level += 1 - for polymorphic_state_set_ in self.polymorphic_state_set: - showIndent(outfile, level) - outfile.write('model_.RNAPolymorphicStateSet(\n') - polymorphic_state_set_.exportLiteral(outfile, level, name_='RNAPolymorphicStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('uncertain_state_set=[\n') - level += 1 - for uncertain_state_set_ in self.uncertain_state_set: - showIndent(outfile, level) - outfile.write('model_.RNAUncertainStateSet(\n') - uncertain_state_set_.exportLiteral(outfile, level, name_='RNAUncertainStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.StateSet(\n') - set_.exportLiteral(outfile, level, name_='StateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RNAStates, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'state': - obj_ = RNAState.factory() - obj_.build(child_) - self.state.append(obj_) - elif nodeName_ == 'polymorphic_state_set': - obj_ = RNAPolymorphicStateSet.factory() - obj_.build(child_) - self.polymorphic_state_set.append(obj_) - elif nodeName_ == 'uncertain_state_set': - obj_ = RNAUncertainStateSet.factory() - obj_.build(child_) - self.uncertain_state_set.append(obj_) - elif nodeName_ == 'set': - obj_ = StateSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class RNAStates - - -class RNAState(AbstractState): - """This is a concrete implementation of the state element, which - requires a symbol attribute, in this case restricted to - RNAToken, i.e. a single IUPAC nucleotide symbol, and optional - mapping elements to refer to other states.""" - subclass = None - superclass = AbstractState - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, valueOf_=None): - super(RNAState, self).__init__(about, meta, label, id, symbol, ) - self.symbol = _cast(None, symbol) - pass - def factory(*args_, **kwargs_): - if RNAState.subclass: - return RNAState.subclass(*args_, **kwargs_) - else: - return RNAState(*args_, **kwargs_) - factory = staticmethod(factory) - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_RNAToken(self, value): - # Validate type RNAToken, a restriction on AbstractSymbol. - pass - def export(self, outfile, level, namespace_='', name_='RNAState', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNAState') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNAState'): - super(RNAState, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNAState') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='RNAState', fromsubclass_=False): - pass - def hasContent_(self): - if ( - super(RNAState, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNAState'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = "%s",\n' % (self.symbol,)) - super(RNAState, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNAState, self).exportLiteralChildren(outfile, level, name_) - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - self.symbol = value - self.validate_RNAToken(self.symbol) # validate type RNAToken - super(RNAState, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class RNAState - - -class RestrictionChar(AbstractChar): - """A concrete implementation of the char element, which requires a - unique identifier and a state set reference.""" - subclass = None - superclass = AbstractChar - def __init__(self, about=None, meta=None, label=None, id=None, tokens=None, states=None, codon=None, valueOf_=None): - super(RestrictionChar, self).__init__(about, meta, label, id, tokens, states, codon, ) - self.tokens = _cast(None, tokens) - self.states = _cast(None, states) - self.codon = _cast(None, codon) - self.id = _cast(None, id) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if RestrictionChar.subclass: - return RestrictionChar.subclass(*args_, **kwargs_) - else: - return RestrictionChar(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_tokens(self): return self.tokens - def set_tokens(self, tokens): self.tokens = tokens - def validate_MSTokenLength(self, value): - # Validate type MSTokenLength, a restriction on xs:positiveInteger. - pass - def get_states(self): return self.states - def set_states(self, states): self.states = states - def get_codon(self): return self.codon - def set_codon(self, codon): self.codon = codon - def validate_CodonPosition(self, value): - # Validate type CodonPosition, a restriction on xs:nonNegativeInteger. - pass - def get_id(self): return self.id - def set_id(self, id): self.id = id - def export(self, outfile, level, namespace_='', name_='RestrictionChar', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionChar') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RestrictionChar'): - super(RestrictionChar, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionChar') - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - outfile.write(' tokens=%s' % (quote_attrib(self.tokens), )) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - outfile.write(' states=%s' % (self.gds_format_string(quote_attrib(self.states).encode(ExternalEncoding), input_name='states'), )) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - outfile.write(' codon=%s' % (quote_attrib(self.codon), )) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) - def exportChildren(self, outfile, level, namespace_='', name_='RestrictionChar', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(RestrictionChar, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RestrictionChar'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - showIndent(outfile, level) - outfile.write('tokens = %d,\n' % (self.tokens,)) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - showIndent(outfile, level) - outfile.write('states = "%s",\n' % (self.states,)) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - showIndent(outfile, level) - outfile.write('codon = %d,\n' % (self.codon,)) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = "%s",\n' % (self.id,)) - super(RestrictionChar, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RestrictionChar, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('tokens', node) - if value is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - try: - self.tokens = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.tokens <= 0: - raise_parse_error(node, 'Invalid PositiveInteger') - self.validate_MSTokenLength(self.tokens) # validate type MSTokenLength - value = find_attr_value_('states', node) - if value is not None and 'states' not in already_processed: - already_processed.append('states') - self.states = value - value = find_attr_value_('codon', node) - if value is not None and 'codon' not in already_processed: - already_processed.append('codon') - try: - self.codon = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.codon < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - self.validate_CodonPosition(self.codon) # validate type CodonPosition - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - self.id = value - super(RestrictionChar, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class RestrictionChar - - -class RestrictionStates(AbstractStates): - """A container for a set of states.""" - subclass = None - superclass = AbstractStates - def __init__(self, about=None, meta=None, label=None, id=None, state=None, polymorphic_state_set=None, uncertain_state_set=None, set=None, valueOf_=None): - super(RestrictionStates, self).__init__(about, meta, label, id, state, polymorphic_state_set, uncertain_state_set, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if state is None: - self.state = [] - else: - self.state = state - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if RestrictionStates.subclass: - return RestrictionStates.subclass(*args_, **kwargs_) - else: - return RestrictionStates(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_state(self): return self.state - def set_state(self, state): self.state = state - def add_state(self, value): self.state.append(value) - def insert_state(self, index, value): self.state[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='RestrictionStates', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionStates') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RestrictionStates'): - super(RestrictionStates, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionStates') - def exportChildren(self, outfile, level, namespace_='', name_='RestrictionStates', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for state_ in self.state: - state_.export(outfile, level, namespace_, name_='state') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.state or - self.set or - super(RestrictionStates, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RestrictionStates'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RestrictionStates, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RestrictionStates, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('state=[\n') - level += 1 - for state_ in self.state: - showIndent(outfile, level) - outfile.write('model_.RestrictionState(\n') - state_.exportLiteral(outfile, level, name_='RestrictionState') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.StateSet(\n') - set_.exportLiteral(outfile, level, name_='StateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RestrictionStates, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'state': - obj_ = RestrictionState.factory() - obj_.build(child_) - self.state.append(obj_) - elif nodeName_ == 'set': - obj_ = StateSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class RestrictionStates - - -class RestrictionState(AbstractState): - """This is a concrete implementation of the state element, which - requires a symbol element, in this case restricted to 0/1.""" - subclass = None - superclass = AbstractState - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, valueOf_=None): - super(RestrictionState, self).__init__(about, meta, label, id, symbol, ) - self.symbol = _cast(None, symbol) - pass - def factory(*args_, **kwargs_): - if RestrictionState.subclass: - return RestrictionState.subclass(*args_, **kwargs_) - else: - return RestrictionState(*args_, **kwargs_) - factory = staticmethod(factory) - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_RestrictionToken(self, value): - # Validate type RestrictionToken, a restriction on xs:integer. - pass - def export(self, outfile, level, namespace_='', name_='RestrictionState', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionState') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RestrictionState'): - super(RestrictionState, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionState') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='RestrictionState', fromsubclass_=False): - pass - def hasContent_(self): - if ( - super(RestrictionState, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RestrictionState'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = %d,\n' % (self.symbol,)) - super(RestrictionState, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RestrictionState, self).exportLiteralChildren(outfile, level, name_) - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - try: - self.symbol = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - self.validate_RestrictionToken(self.symbol) # validate type RestrictionToken - super(RestrictionState, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class RestrictionState - - -class AAState(AbstractState): - """This is a concrete implementation of the state element, which - requires a symbol element, in this case restricted to AAToken, - i.e. a single IUPAC amino acid symbol, and optional mapping - elements to refer to other states.""" - subclass = None - superclass = AbstractState - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, valueOf_=None): - super(AAState, self).__init__(about, meta, label, id, symbol, ) - self.symbol = _cast(None, symbol) - pass - def factory(*args_, **kwargs_): - if AAState.subclass: - return AAState.subclass(*args_, **kwargs_) - else: - return AAState(*args_, **kwargs_) - factory = staticmethod(factory) - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_AAToken(self, value): - # Validate type AAToken, a restriction on AbstractSymbol. - pass - def export(self, outfile, level, namespace_='', name_='AAState', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AAState') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AAState'): - super(AAState, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AAState') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='AAState', fromsubclass_=False): - pass - def hasContent_(self): - if ( - super(AAState, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AAState'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = "%s",\n' % (self.symbol,)) - super(AAState, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AAState, self).exportLiteralChildren(outfile, level, name_) - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - self.symbol = value - self.validate_AAToken(self.symbol) # validate type AAToken - super(AAState, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class AAState - - -class AAStates(AbstractStates): - """A container for a set of states.""" - subclass = None - superclass = AbstractStates - def __init__(self, about=None, meta=None, label=None, id=None, state=None, polymorphic_state_set=None, uncertain_state_set=None, set=None, valueOf_=None): - super(AAStates, self).__init__(about, meta, label, id, state, polymorphic_state_set, uncertain_state_set, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if state is None: - self.state = [] - else: - self.state = state - if polymorphic_state_set is None: - self.polymorphic_state_set = [] - else: - self.polymorphic_state_set = polymorphic_state_set - if uncertain_state_set is None: - self.uncertain_state_set = [] - else: - self.uncertain_state_set = uncertain_state_set - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AAStates.subclass: - return AAStates.subclass(*args_, **kwargs_) - else: - return AAStates(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_state(self): return self.state - def set_state(self, state): self.state = state - def add_state(self, value): self.state.append(value) - def insert_state(self, index, value): self.state[index] = value - def get_polymorphic_state_set(self): return self.polymorphic_state_set - def set_polymorphic_state_set(self, polymorphic_state_set): self.polymorphic_state_set = polymorphic_state_set - def add_polymorphic_state_set(self, value): self.polymorphic_state_set.append(value) - def insert_polymorphic_state_set(self, index, value): self.polymorphic_state_set[index] = value - def get_uncertain_state_set(self): return self.uncertain_state_set - def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set - def add_uncertain_state_set(self, value): self.uncertain_state_set.append(value) - def insert_uncertain_state_set(self, index, value): self.uncertain_state_set[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AAStates', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AAStates') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AAStates'): - super(AAStates, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AAStates') - def exportChildren(self, outfile, level, namespace_='', name_='AAStates', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for state_ in self.state: - state_.export(outfile, level, namespace_, name_='state') - for polymorphic_state_set_ in self.polymorphic_state_set: - polymorphic_state_set_.export(outfile, level, namespace_, name_='polymorphic_state_set') - for uncertain_state_set_ in self.uncertain_state_set: - uncertain_state_set_.export(outfile, level, namespace_, name_='uncertain_state_set') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.state or - self.polymorphic_state_set or - self.uncertain_state_set or - self.set or - super(AAStates, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AAStates'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AAStates, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AAStates, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('state=[\n') - level += 1 - for state_ in self.state: - showIndent(outfile, level) - outfile.write('model_.AAState(\n') - state_.exportLiteral(outfile, level, name_='AAState') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('polymorphic_state_set=[\n') - level += 1 - for polymorphic_state_set_ in self.polymorphic_state_set: - showIndent(outfile, level) - outfile.write('model_.AAPolymorphicStateSet(\n') - polymorphic_state_set_.exportLiteral(outfile, level, name_='AAPolymorphicStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('uncertain_state_set=[\n') - level += 1 - for uncertain_state_set_ in self.uncertain_state_set: - showIndent(outfile, level) - outfile.write('model_.AAUncertainStateSet(\n') - uncertain_state_set_.exportLiteral(outfile, level, name_='AAUncertainStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.StateSet(\n') - set_.exportLiteral(outfile, level, name_='StateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AAStates, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'state': - obj_ = AAState.factory() - obj_.build(child_) - self.state.append(obj_) - elif nodeName_ == 'polymorphic_state_set': - obj_ = AAPolymorphicStateSet.factory() - obj_.build(child_) - self.polymorphic_state_set.append(obj_) - elif nodeName_ == 'uncertain_state_set': - obj_ = AAUncertainStateSet.factory() - obj_.build(child_) - self.uncertain_state_set.append(obj_) - elif nodeName_ == 'set': - obj_ = StateSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class AAStates - - -class AAChar(AbstractChar): - """A concrete implementation of the AbstractChar element.""" - subclass = None - superclass = AbstractChar - def __init__(self, about=None, meta=None, label=None, id=None, tokens=None, states=None, codon=None, valueOf_=None): - super(AAChar, self).__init__(about, meta, label, id, tokens, states, codon, ) - self.tokens = _cast(None, tokens) - self.states = _cast(None, states) - self.codon = _cast(None, codon) - self.id = _cast(None, id) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if AAChar.subclass: - return AAChar.subclass(*args_, **kwargs_) - else: - return AAChar(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_tokens(self): return self.tokens - def set_tokens(self, tokens): self.tokens = tokens - def validate_MSTokenLength(self, value): - # Validate type MSTokenLength, a restriction on xs:positiveInteger. - pass - def get_states(self): return self.states - def set_states(self, states): self.states = states - def get_codon(self): return self.codon - def set_codon(self, codon): self.codon = codon - def validate_CodonPosition(self, value): - # Validate type CodonPosition, a restriction on xs:nonNegativeInteger. - pass - def get_id(self): return self.id - def set_id(self, id): self.id = id - def export(self, outfile, level, namespace_='', name_='AAChar', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AAChar') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AAChar'): - super(AAChar, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AAChar') - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - outfile.write(' tokens=%s' % (quote_attrib(self.tokens), )) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - outfile.write(' states=%s' % (self.gds_format_string(quote_attrib(self.states).encode(ExternalEncoding), input_name='states'), )) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - outfile.write(' codon=%s' % (quote_attrib(self.codon), )) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) - def exportChildren(self, outfile, level, namespace_='', name_='AAChar', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(AAChar, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AAChar'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - showIndent(outfile, level) - outfile.write('tokens = %d,\n' % (self.tokens,)) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - showIndent(outfile, level) - outfile.write('states = "%s",\n' % (self.states,)) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - showIndent(outfile, level) - outfile.write('codon = %d,\n' % (self.codon,)) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = "%s",\n' % (self.id,)) - super(AAChar, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AAChar, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('tokens', node) - if value is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - try: - self.tokens = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.tokens <= 0: - raise_parse_error(node, 'Invalid PositiveInteger') - self.validate_MSTokenLength(self.tokens) # validate type MSTokenLength - value = find_attr_value_('states', node) - if value is not None and 'states' not in already_processed: - already_processed.append('states') - self.states = value - value = find_attr_value_('codon', node) - if value is not None and 'codon' not in already_processed: - already_processed.append('codon') - try: - self.codon = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.codon < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - self.validate_CodonPosition(self.codon) # validate type CodonPosition - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - self.id = value - super(AAChar, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class AAChar - - -class DNAChar(AbstractChar): - """A concrete implementation of the AbstractChar element.""" - subclass = None - superclass = AbstractChar - def __init__(self, about=None, meta=None, label=None, id=None, tokens=None, states=None, codon=None, valueOf_=None): - super(DNAChar, self).__init__(about, meta, label, id, tokens, states, codon, ) - self.tokens = _cast(None, tokens) - self.states = _cast(None, states) - self.codon = _cast(None, codon) - self.id = _cast(None, id) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if DNAChar.subclass: - return DNAChar.subclass(*args_, **kwargs_) - else: - return DNAChar(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_tokens(self): return self.tokens - def set_tokens(self, tokens): self.tokens = tokens - def validate_MSTokenLength(self, value): - # Validate type MSTokenLength, a restriction on xs:positiveInteger. - pass - def get_states(self): return self.states - def set_states(self, states): self.states = states - def get_codon(self): return self.codon - def set_codon(self, codon): self.codon = codon - def validate_CodonPosition(self, value): - # Validate type CodonPosition, a restriction on xs:nonNegativeInteger. - pass - def get_id(self): return self.id - def set_id(self, id): self.id = id - def export(self, outfile, level, namespace_='', name_='DNAChar', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNAChar') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNAChar'): - super(DNAChar, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNAChar') - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - outfile.write(' tokens=%s' % (quote_attrib(self.tokens), )) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - outfile.write(' states=%s' % (self.gds_format_string(quote_attrib(self.states).encode(ExternalEncoding), input_name='states'), )) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - outfile.write(' codon=%s' % (quote_attrib(self.codon), )) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) - def exportChildren(self, outfile, level, namespace_='', name_='DNAChar', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(DNAChar, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNAChar'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.tokens is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - showIndent(outfile, level) - outfile.write('tokens = %d,\n' % (self.tokens,)) - if self.states is not None and 'states' not in already_processed: - already_processed.append('states') - showIndent(outfile, level) - outfile.write('states = "%s",\n' % (self.states,)) - if self.codon is not None and 'codon' not in already_processed: - already_processed.append('codon') - showIndent(outfile, level) - outfile.write('codon = %d,\n' % (self.codon,)) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = "%s",\n' % (self.id,)) - super(DNAChar, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNAChar, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('tokens', node) - if value is not None and 'tokens' not in already_processed: - already_processed.append('tokens') - try: - self.tokens = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.tokens <= 0: - raise_parse_error(node, 'Invalid PositiveInteger') - self.validate_MSTokenLength(self.tokens) # validate type MSTokenLength - value = find_attr_value_('states', node) - if value is not None and 'states' not in already_processed: - already_processed.append('states') - self.states = value - value = find_attr_value_('codon', node) - if value is not None and 'codon' not in already_processed: - already_processed.append('codon') - try: - self.codon = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.codon < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - self.validate_CodonPosition(self.codon) # validate type CodonPosition - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - self.id = value - super(DNAChar, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class DNAChar - - -class DNAStates(AbstractStates): - """A container for a set of states.""" - subclass = None - superclass = AbstractStates - def __init__(self, about=None, meta=None, label=None, id=None, state=None, polymorphic_state_set=None, uncertain_state_set=None, set=None, valueOf_=None): - super(DNAStates, self).__init__(about, meta, label, id, state, polymorphic_state_set, uncertain_state_set, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if state is None: - self.state = [] - else: - self.state = state - if polymorphic_state_set is None: - self.polymorphic_state_set = [] - else: - self.polymorphic_state_set = polymorphic_state_set - if uncertain_state_set is None: - self.uncertain_state_set = [] - else: - self.uncertain_state_set = uncertain_state_set - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if DNAStates.subclass: - return DNAStates.subclass(*args_, **kwargs_) - else: - return DNAStates(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_state(self): return self.state - def set_state(self, state): self.state = state - def add_state(self, value): self.state.append(value) - def insert_state(self, index, value): self.state[index] = value - def get_polymorphic_state_set(self): return self.polymorphic_state_set - def set_polymorphic_state_set(self, polymorphic_state_set): self.polymorphic_state_set = polymorphic_state_set - def add_polymorphic_state_set(self, value): self.polymorphic_state_set.append(value) - def insert_polymorphic_state_set(self, index, value): self.polymorphic_state_set[index] = value - def get_uncertain_state_set(self): return self.uncertain_state_set - def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set - def add_uncertain_state_set(self, value): self.uncertain_state_set.append(value) - def insert_uncertain_state_set(self, index, value): self.uncertain_state_set[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='DNAStates', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNAStates') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNAStates'): - super(DNAStates, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNAStates') - def exportChildren(self, outfile, level, namespace_='', name_='DNAStates', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for state_ in self.state: - state_.export(outfile, level, namespace_, name_='state') - for polymorphic_state_set_ in self.polymorphic_state_set: - polymorphic_state_set_.export(outfile, level, namespace_, name_='polymorphic_state_set') - for uncertain_state_set_ in self.uncertain_state_set: - uncertain_state_set_.export(outfile, level, namespace_, name_='uncertain_state_set') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.state or - self.polymorphic_state_set or - self.uncertain_state_set or - self.set or - super(DNAStates, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNAStates'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(DNAStates, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNAStates, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('state=[\n') - level += 1 - for state_ in self.state: - showIndent(outfile, level) - outfile.write('model_.DNAState(\n') - state_.exportLiteral(outfile, level, name_='DNAState') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('polymorphic_state_set=[\n') - level += 1 - for polymorphic_state_set_ in self.polymorphic_state_set: - showIndent(outfile, level) - outfile.write('model_.DNAPolymorphicStateSet(\n') - polymorphic_state_set_.exportLiteral(outfile, level, name_='DNAPolymorphicStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('uncertain_state_set=[\n') - level += 1 - for uncertain_state_set_ in self.uncertain_state_set: - showIndent(outfile, level) - outfile.write('model_.DNAUncertainStateSet(\n') - uncertain_state_set_.exportLiteral(outfile, level, name_='DNAUncertainStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.StateSet(\n') - set_.exportLiteral(outfile, level, name_='StateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(DNAStates, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'state': - obj_ = DNAState.factory() - obj_.build(child_) - self.state.append(obj_) - elif nodeName_ == 'polymorphic_state_set': - obj_ = DNAPolymorphicStateSet.factory() - obj_.build(child_) - self.polymorphic_state_set.append(obj_) - elif nodeName_ == 'uncertain_state_set': - obj_ = DNAUncertainStateSet.factory() - obj_.build(child_) - self.uncertain_state_set.append(obj_) - elif nodeName_ == 'set': - obj_ = StateSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class DNAStates - - -class DNAState(AbstractState): - """This is a concrete implementation of the state element, which - requires a symbol element, in this case restricted to DNAToken, - i.e. a single IUPAC nucleotide symbol, and optional mapping - elements to refer to other states.""" - subclass = None - superclass = AbstractState - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, valueOf_=None): - super(DNAState, self).__init__(about, meta, label, id, symbol, ) - self.symbol = _cast(None, symbol) - pass - def factory(*args_, **kwargs_): - if DNAState.subclass: - return DNAState.subclass(*args_, **kwargs_) - else: - return DNAState(*args_, **kwargs_) - factory = staticmethod(factory) - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_DNAToken(self, value): - # Validate type DNAToken, a restriction on AbstractSymbol. - pass - def export(self, outfile, level, namespace_='', name_='DNAState', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNAState') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNAState'): - super(DNAState, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNAState') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='DNAState', fromsubclass_=False): - pass - def hasContent_(self): - if ( - super(DNAState, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNAState'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = "%s",\n' % (self.symbol,)) - super(DNAState, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNAState, self).exportLiteralChildren(outfile, level, name_) - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - self.symbol = value - self.validate_DNAToken(self.symbol) # validate type DNAToken - super(DNAState, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class DNAState - - -class AbstractBlock(TaxaLinked): - """The AbstractBlock is the superclass for blocks that contain an - element structure of type AbstractFormat.""" - subclass = None - superclass = TaxaLinked - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, valueOf_=None): - super(AbstractBlock, self).__init__(about, meta, label, id, otus, ) - self.format = format - def factory(*args_, **kwargs_): - if AbstractBlock.subclass: - return AbstractBlock.subclass(*args_, **kwargs_) - else: - return AbstractBlock(*args_, **kwargs_) - factory = staticmethod(factory) - def get_format(self): return self.format - def set_format(self, format): self.format = format - def export(self, outfile, level, namespace_='', name_='AbstractBlock', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractBlock') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractBlock"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractBlock'): - super(AbstractBlock, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractBlock') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractBlock', fromsubclass_=False): - super(AbstractBlock, self).exportChildren(outfile, level, namespace_, name_, True) - format_.export(outfile, level, namespace_, name_='format') - def hasContent_(self): - if ( - self.format is not None or - super(AbstractBlock, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractBlock'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractBlock, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractBlock, self).exportLiteralChildren(outfile, level, name_) - if self.AbstractFormat is not None: - showIndent(outfile, level) - outfile.write('AbstractFormat=model_.AbstractFormat(\n') - self.AbstractFormat.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractBlock, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'format': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.set_format(obj_) - super(AbstractBlock, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractBlock - - -class AbstractObsRow(TaxonLinked): - """The AbstractObsRow represents a single row in a matrix. The row must - refer to a previously declared otu element by its id attribute - (and must have an id itself, may have a label, and may have meta - attachments). The row contains multiple cell elements.""" - subclass = None - superclass = TaxonLinked - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, cell=None, set=None, valueOf_=None): - super(AbstractObsRow, self).__init__(about, meta, label, id, otu, ) - if cell is None: - self.cell = [] - else: - self.cell = cell - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AbstractObsRow.subclass: - return AbstractObsRow.subclass(*args_, **kwargs_) - else: - return AbstractObsRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_cell(self): return self.cell - def set_cell(self, cell): self.cell = cell - def add_cell(self, value): self.cell.append(value) - def insert_cell(self, index, value): self.cell[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AbstractObsRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractObsRow') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractObsRow"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractObsRow'): - super(AbstractObsRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractObsRow') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractObsRow', fromsubclass_=False): - super(AbstractObsRow, self).exportChildren(outfile, level, namespace_, name_, True) - for cell_ in self.get_cell(): - cell_.export(outfile, level, namespace_, name_='cell') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.cell or - self.set or - super(AbstractObsRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractObsRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractObsRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractObsRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('cell=[\n') - level += 1 - for cell_ in self.cell: - showIndent(outfile, level) - outfile.write('model_.AbstractObs(\n') - cell_.exportLiteral(outfile, level, name_='AbstractObs') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CellSet(\n') - set_.exportLiteral(outfile, level, name_='CellSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractObsRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'cell': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.cell.append(obj_) - elif nodeName_ == 'set': - obj_ = CellSet.factory() - obj_.build(child_) - self.set.append(obj_) - super(AbstractObsRow, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractObsRow - - -class AbstractSeqRow(TaxonLinked): - """The AbstractSeqRow represents a single row in a matrix. The row must - refer to a previously declared otu element by its id attribute - (and must have an id itself, may have a label, and may have meta - attachments). The row contains a single seq element with raw - character data.""" - subclass = None - superclass = TaxonLinked - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, seq=None, valueOf_=None): - super(AbstractSeqRow, self).__init__(about, meta, label, id, otu, ) - self.seq = seq - def factory(*args_, **kwargs_): - if AbstractSeqRow.subclass: - return AbstractSeqRow.subclass(*args_, **kwargs_) - else: - return AbstractSeqRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_seq(self): return self.seq - def set_seq(self, seq): self.seq = seq - def export(self, outfile, level, namespace_='', name_='AbstractSeqRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractSeqRow') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractSeqRow"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractSeqRow'): - super(AbstractSeqRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractSeqRow') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractSeqRow', fromsubclass_=False): - super(AbstractSeqRow, self).exportChildren(outfile, level, namespace_, name_, True) - if self.seq: - self.seq.export(outfile, level, namespace_, name_='seq', ) - def hasContent_(self): - if ( - self.seq is not None or - super(AbstractSeqRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractSeqRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractSeqRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractSeqRow, self).exportLiteralChildren(outfile, level, name_) - if self.seq is not None: - showIndent(outfile, level) - outfile.write('seq=model_.xs_anySimpleType(\n') - self.seq.exportLiteral(outfile, level, name_='seq') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractSeqRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'seq': - obj_ = xs_anySimpleType.factory() - obj_.build(child_) - self.set_seq(obj_) - super(AbstractSeqRow, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractSeqRow - - -class AbstractUncertainStateSet(AbstractState): - """The AbstractUncertainStateSet type is the super-class for an - uncertain state set definition. The element has a required - AbstractSymbol attribute that in restricted concrete subclasses - must be of a sensible type such as a single IUPAC character. It - may enclose zero or more AbstractMapping elements to resolve - ambiguities.""" - subclass = None - superclass = AbstractState - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, member=None, valueOf_=None): - super(AbstractUncertainStateSet, self).__init__(about, meta, label, id, symbol, ) - if member is None: - self.member = [] - else: - self.member = member - def factory(*args_, **kwargs_): - if AbstractUncertainStateSet.subclass: - return AbstractUncertainStateSet.subclass(*args_, **kwargs_) - else: - return AbstractUncertainStateSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_member(self): return self.member - def set_member(self, member): self.member = member - def add_member(self, value): self.member.append(value) - def insert_member(self, index, value): self.member[index] = value - def export(self, outfile, level, namespace_='', name_='AbstractUncertainStateSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractUncertainStateSet') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractUncertainStateSet"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractUncertainStateSet'): - super(AbstractUncertainStateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractUncertainStateSet') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractUncertainStateSet', fromsubclass_=False): - super(AbstractUncertainStateSet, self).exportChildren(outfile, level, namespace_, name_, True) - for member_ in self.get_member(): - member_.export(outfile, level, namespace_, name_='member') - def hasContent_(self): - if ( - self.member or - super(AbstractUncertainStateSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractUncertainStateSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractUncertainStateSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractUncertainStateSet, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('member=[\n') - level += 1 - for member_ in self.member: - showIndent(outfile, level) - outfile.write('model_.AbstractMapping(\n') - member_.exportLiteral(outfile, level, name_='AbstractMapping') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractUncertainStateSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'member': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.member.append(obj_) - super(AbstractUncertainStateSet, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractUncertainStateSet - - -class ContinuousMatrixObsRow(AbstractObsRow): - """This is a row in a matrix of continuous data as granular - obervations.""" - subclass = None - superclass = AbstractObsRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, cell=None, set=None, valueOf_=None): - super(ContinuousMatrixObsRow, self).__init__(about, meta, label, id, otu, cell, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if cell is None: - self.cell = [] - else: - self.cell = cell - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if ContinuousMatrixObsRow.subclass: - return ContinuousMatrixObsRow.subclass(*args_, **kwargs_) - else: - return ContinuousMatrixObsRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_cell(self): return self.cell - def set_cell(self, cell): self.cell = cell - def add_cell(self, value): self.cell.append(value) - def insert_cell(self, index, value): self.cell[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='ContinuousMatrixObsRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousMatrixObsRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ContinuousMatrixObsRow'): - super(ContinuousMatrixObsRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousMatrixObsRow') - def exportChildren(self, outfile, level, namespace_='', name_='ContinuousMatrixObsRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for cell_ in self.cell: - cell_.export(outfile, level, namespace_, name_='cell') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.cell or - self.set or - super(ContinuousMatrixObsRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ContinuousMatrixObsRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(ContinuousMatrixObsRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ContinuousMatrixObsRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('cell=[\n') - level += 1 - for cell_ in self.cell: - showIndent(outfile, level) - outfile.write('model_.ContinuousObs(\n') - cell_.exportLiteral(outfile, level, name_='ContinuousObs') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CellSet(\n') - set_.exportLiteral(outfile, level, name_='CellSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(ContinuousMatrixObsRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'cell': - obj_ = ContinuousObs.factory() - obj_.build(child_) - self.cell.append(obj_) - elif nodeName_ == 'set': - obj_ = CellSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class ContinuousMatrixObsRow - - -class ContinuousMatrixSeqRow(AbstractSeqRow): - """This is a row in a matrix of continuous data as character sequences.""" - subclass = None - superclass = AbstractSeqRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, seq=None, valueOf_=None): - super(ContinuousMatrixSeqRow, self).__init__(about, meta, label, id, otu, seq, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.seq = seq - def factory(*args_, **kwargs_): - if ContinuousMatrixSeqRow.subclass: - return ContinuousMatrixSeqRow.subclass(*args_, **kwargs_) - else: - return ContinuousMatrixSeqRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_seq(self): return self.seq - def set_seq(self, seq): self.seq = seq - def validate_ContinuousSeq(self, value): - # Validate type ContinuousSeq, a restriction on AbstractTokenList. - pass - def export(self, outfile, level, namespace_='', name_='ContinuousMatrixSeqRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousMatrixSeqRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ContinuousMatrixSeqRow'): - super(ContinuousMatrixSeqRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousMatrixSeqRow') - def exportChildren(self, outfile, level, namespace_='', name_='ContinuousMatrixSeqRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('<%sseq>%s\n' % (namespace_, self.gds_format_double_list(self.seq, input_name='seq'), namespace_)) - def hasContent_(self): - if ( - self.meta or - self.seq is not None or - super(ContinuousMatrixSeqRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ContinuousMatrixSeqRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(ContinuousMatrixSeqRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ContinuousMatrixSeqRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('seq=%e,\n' % self.seq) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(ContinuousMatrixSeqRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'seq': - seq_ = child_.text - seq_ = self.gds_validate_double_list(seq_, node, 'seq') - self.seq = seq_ - self.validate_ContinuousSeq(self.seq) # validate type ContinuousSeq -# end class ContinuousMatrixSeqRow - - -class NodeAndRootEdgeAndEdgeSet(AbstractSet): - subclass = None - superclass = AbstractSet - def __init__(self, about=None, meta=None, label=None, id=None, node=None, edge=None, rootedge=None, valueOf_=None): - super(NodeAndRootEdgeAndEdgeSet, self).__init__(about, meta, label, id, ) - self.node = _cast(None, node) - self.edge = _cast(None, edge) - self.rootedge = _cast(None, rootedge) - pass - def factory(*args_, **kwargs_): - if NodeAndRootEdgeAndEdgeSet.subclass: - return NodeAndRootEdgeAndEdgeSet.subclass(*args_, **kwargs_) - else: - return NodeAndRootEdgeAndEdgeSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_node(self): return self.node - def set_node(self, node): self.node = node - def get_edge(self): return self.edge - def set_edge(self, edge): self.edge = edge - def get_rootedge(self): return self.rootedge - def set_rootedge(self, rootedge): self.rootedge = rootedge - def export(self, outfile, level, namespace_='', name_='NodeAndRootEdgeAndEdgeSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='NodeAndRootEdgeAndEdgeSet') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="NodeAndRootEdgeAndEdgeSet"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='NodeAndRootEdgeAndEdgeSet'): - super(NodeAndRootEdgeAndEdgeSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='NodeAndRootEdgeAndEdgeSet') - if self.node is not None and 'node' not in already_processed: - already_processed.append('node') - outfile.write(' node=%s' % (self.gds_format_string(quote_attrib(self.node).encode(ExternalEncoding), input_name='node'), )) - if self.edge is not None and 'edge' not in already_processed: - already_processed.append('edge') - outfile.write(' edge=%s' % (self.gds_format_string(quote_attrib(self.edge).encode(ExternalEncoding), input_name='edge'), )) - if self.rootedge is not None and 'rootedge' not in already_processed: - already_processed.append('rootedge') - outfile.write(' rootedge=%s' % (self.gds_format_string(quote_attrib(self.rootedge).encode(ExternalEncoding), input_name='rootedge'), )) - def exportChildren(self, outfile, level, namespace_='', name_='NodeAndRootEdgeAndEdgeSet', fromsubclass_=False): - super(NodeAndRootEdgeAndEdgeSet, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(NodeAndRootEdgeAndEdgeSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='NodeAndRootEdgeAndEdgeSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.node is not None and 'node' not in already_processed: - already_processed.append('node') - showIndent(outfile, level) - outfile.write('node = "%s",\n' % (self.node,)) - if self.edge is not None and 'edge' not in already_processed: - already_processed.append('edge') - showIndent(outfile, level) - outfile.write('edge = "%s",\n' % (self.edge,)) - if self.rootedge is not None and 'rootedge' not in already_processed: - already_processed.append('rootedge') - showIndent(outfile, level) - outfile.write('rootedge = "%s",\n' % (self.rootedge,)) - super(NodeAndRootEdgeAndEdgeSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(NodeAndRootEdgeAndEdgeSet, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('node', node) - if value is not None and 'node' not in already_processed: - already_processed.append('node') - self.node = value - value = find_attr_value_('edge', node) - if value is not None and 'edge' not in already_processed: - already_processed.append('edge') - self.edge = value - value = find_attr_value_('rootedge', node) - if value is not None and 'rootedge' not in already_processed: - already_processed.append('rootedge') - self.rootedge = value - super(NodeAndRootEdgeAndEdgeSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(NodeAndRootEdgeAndEdgeSet, self).buildChildren(child_, node, nodeName_, True) - pass -# end class NodeAndRootEdgeAndEdgeSet - - -class TreeAndNetworkSet(AbstractSet): - subclass = None - superclass = AbstractSet - def __init__(self, about=None, meta=None, label=None, id=None, tree=None, network=None, valueOf_=None): - super(TreeAndNetworkSet, self).__init__(about, meta, label, id, ) - self.tree = _cast(None, tree) - self.network = _cast(None, network) - pass - def factory(*args_, **kwargs_): - if TreeAndNetworkSet.subclass: - return TreeAndNetworkSet.subclass(*args_, **kwargs_) - else: - return TreeAndNetworkSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_tree(self): return self.tree - def set_tree(self, tree): self.tree = tree - def get_network(self): return self.network - def set_network(self, network): self.network = network - def export(self, outfile, level, namespace_='', name_='TreeAndNetworkSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='TreeAndNetworkSet') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="TreeAndNetworkSet"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='TreeAndNetworkSet'): - super(TreeAndNetworkSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='TreeAndNetworkSet') - if self.tree is not None and 'tree' not in already_processed: - already_processed.append('tree') - outfile.write(' tree=%s' % (self.gds_format_string(quote_attrib(self.tree).encode(ExternalEncoding), input_name='tree'), )) - if self.network is not None and 'network' not in already_processed: - already_processed.append('network') - outfile.write(' network=%s' % (self.gds_format_string(quote_attrib(self.network).encode(ExternalEncoding), input_name='network'), )) - def exportChildren(self, outfile, level, namespace_='', name_='TreeAndNetworkSet', fromsubclass_=False): - super(TreeAndNetworkSet, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(TreeAndNetworkSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='TreeAndNetworkSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.tree is not None and 'tree' not in already_processed: - already_processed.append('tree') - showIndent(outfile, level) - outfile.write('tree = "%s",\n' % (self.tree,)) - if self.network is not None and 'network' not in already_processed: - already_processed.append('network') - showIndent(outfile, level) - outfile.write('network = "%s",\n' % (self.network,)) - super(TreeAndNetworkSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(TreeAndNetworkSet, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('tree', node) - if value is not None and 'tree' not in already_processed: - already_processed.append('tree') - self.tree = value - value = find_attr_value_('network', node) - if value is not None and 'network' not in already_processed: - already_processed.append('network') - self.network = value - super(TreeAndNetworkSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(TreeAndNetworkSet, self).buildChildren(child_, node, nodeName_, True) - pass -# end class TreeAndNetworkSet - - -class CellSet(AbstractSet): - subclass = None - superclass = AbstractSet - def __init__(self, about=None, meta=None, label=None, id=None, cell=None, valueOf_=None): - super(CellSet, self).__init__(about, meta, label, id, ) - self.cell = _cast(None, cell) - pass - def factory(*args_, **kwargs_): - if CellSet.subclass: - return CellSet.subclass(*args_, **kwargs_) - else: - return CellSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_cell(self): return self.cell - def set_cell(self, cell): self.cell = cell - def export(self, outfile, level, namespace_='', name_='CellSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='CellSet') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="CellSet"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='CellSet'): - super(CellSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='CellSet') - if self.cell is not None and 'cell' not in already_processed: - already_processed.append('cell') - outfile.write(' cell=%s' % (self.gds_format_string(quote_attrib(self.cell).encode(ExternalEncoding), input_name='cell'), )) - def exportChildren(self, outfile, level, namespace_='', name_='CellSet', fromsubclass_=False): - super(CellSet, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(CellSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='CellSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.cell is not None and 'cell' not in already_processed: - already_processed.append('cell') - showIndent(outfile, level) - outfile.write('cell = "%s",\n' % (self.cell,)) - super(CellSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(CellSet, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('cell', node) - if value is not None and 'cell' not in already_processed: - already_processed.append('cell') - self.cell = value - super(CellSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(CellSet, self).buildChildren(child_, node, nodeName_, True) - pass -# end class CellSet - - -class RowSet(AbstractSet): - subclass = None - superclass = AbstractSet - def __init__(self, about=None, meta=None, label=None, id=None, row=None, valueOf_=None): - super(RowSet, self).__init__(about, meta, label, id, ) - self.row = _cast(None, row) - pass - def factory(*args_, **kwargs_): - if RowSet.subclass: - return RowSet.subclass(*args_, **kwargs_) - else: - return RowSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_row(self): return self.row - def set_row(self, row): self.row = row - def export(self, outfile, level, namespace_='', name_='RowSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RowSet') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="RowSet"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RowSet'): - super(RowSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RowSet') - if self.row is not None and 'row' not in already_processed: - already_processed.append('row') - outfile.write(' row=%s' % (self.gds_format_string(quote_attrib(self.row).encode(ExternalEncoding), input_name='row'), )) - def exportChildren(self, outfile, level, namespace_='', name_='RowSet', fromsubclass_=False): - super(RowSet, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(RowSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RowSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.row is not None and 'row' not in already_processed: - already_processed.append('row') - showIndent(outfile, level) - outfile.write('row = "%s",\n' % (self.row,)) - super(RowSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RowSet, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('row', node) - if value is not None and 'row' not in already_processed: - already_processed.append('row') - self.row = value - super(RowSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(RowSet, self).buildChildren(child_, node, nodeName_, True) - pass -# end class RowSet - - -class CharSet(AbstractSet): - subclass = None - superclass = AbstractSet - def __init__(self, about=None, meta=None, label=None, id=None, char=None, valueOf_=None): - super(CharSet, self).__init__(about, meta, label, id, ) - self.char = _cast(None, char) - pass - def factory(*args_, **kwargs_): - if CharSet.subclass: - return CharSet.subclass(*args_, **kwargs_) - else: - return CharSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_char(self): return self.char - def set_char(self, char): self.char = char - def export(self, outfile, level, namespace_='', name_='CharSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='CharSet') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="CharSet"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='CharSet'): - super(CharSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='CharSet') - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - outfile.write(' char=%s' % (self.gds_format_string(quote_attrib(self.char).encode(ExternalEncoding), input_name='char'), )) - def exportChildren(self, outfile, level, namespace_='', name_='CharSet', fromsubclass_=False): - super(CharSet, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(CharSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='CharSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.char is not None and 'char' not in already_processed: - already_processed.append('char') - showIndent(outfile, level) - outfile.write('char = "%s",\n' % (self.char,)) - super(CharSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(CharSet, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('char', node) - if value is not None and 'char' not in already_processed: - already_processed.append('char') - self.char = value - super(CharSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(CharSet, self).buildChildren(child_, node, nodeName_, True) - pass -# end class CharSet - - -class StateSet(AbstractSet): - subclass = None - superclass = AbstractSet - def __init__(self, about=None, meta=None, label=None, id=None, uncertain_state_set=None, state=None, polymorphic_state_set=None, valueOf_=None): - super(StateSet, self).__init__(about, meta, label, id, ) - self.uncertain_state_set = _cast(None, uncertain_state_set) - self.state = _cast(None, state) - self.polymorphic_state_set = _cast(None, polymorphic_state_set) - pass - def factory(*args_, **kwargs_): - if StateSet.subclass: - return StateSet.subclass(*args_, **kwargs_) - else: - return StateSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_uncertain_state_set(self): return self.uncertain_state_set - def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set - def get_state(self): return self.state - def set_state(self, state): self.state = state - def get_polymorphic_state_set(self): return self.polymorphic_state_set - def set_polymorphic_state_set(self, polymorphic_state_set): self.polymorphic_state_set = polymorphic_state_set - def export(self, outfile, level, namespace_='', name_='StateSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StateSet') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="StateSet"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StateSet'): - super(StateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StateSet') - if self.uncertain_state_set is not None and 'uncertain_state_set' not in already_processed: - already_processed.append('uncertain_state_set') - outfile.write(' uncertain_state_set=%s' % (self.gds_format_string(quote_attrib(self.uncertain_state_set).encode(ExternalEncoding), input_name='uncertain_state_set'), )) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - outfile.write(' state=%s' % (self.gds_format_string(quote_attrib(self.state).encode(ExternalEncoding), input_name='state'), )) - if self.polymorphic_state_set is not None and 'polymorphic_state_set' not in already_processed: - already_processed.append('polymorphic_state_set') - outfile.write(' polymorphic_state_set=%s' % (self.gds_format_string(quote_attrib(self.polymorphic_state_set).encode(ExternalEncoding), input_name='polymorphic_state_set'), )) - def exportChildren(self, outfile, level, namespace_='', name_='StateSet', fromsubclass_=False): - super(StateSet, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(StateSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StateSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.uncertain_state_set is not None and 'uncertain_state_set' not in already_processed: - already_processed.append('uncertain_state_set') - showIndent(outfile, level) - outfile.write('uncertain_state_set = "%s",\n' % (self.uncertain_state_set,)) - if self.state is not None and 'state' not in already_processed: - already_processed.append('state') - showIndent(outfile, level) - outfile.write('state = "%s",\n' % (self.state,)) - if self.polymorphic_state_set is not None and 'polymorphic_state_set' not in already_processed: - already_processed.append('polymorphic_state_set') - showIndent(outfile, level) - outfile.write('polymorphic_state_set = "%s",\n' % (self.polymorphic_state_set,)) - super(StateSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StateSet, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('uncertain_state_set', node) - if value is not None and 'uncertain_state_set' not in already_processed: - already_processed.append('uncertain_state_set') - self.uncertain_state_set = value - value = find_attr_value_('state', node) - if value is not None and 'state' not in already_processed: - already_processed.append('state') - self.state = value - value = find_attr_value_('polymorphic_state_set', node) - if value is not None and 'polymorphic_state_set' not in already_processed: - already_processed.append('polymorphic_state_set') - self.polymorphic_state_set = value - super(StateSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(StateSet, self).buildChildren(child_, node, nodeName_, True) - pass -# end class StateSet - - -class TaxonSet(AbstractSet): - subclass = None - superclass = AbstractSet - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, valueOf_=None): - super(TaxonSet, self).__init__(about, meta, label, id, ) - self.otu = _cast(None, otu) - pass - def factory(*args_, **kwargs_): - if TaxonSet.subclass: - return TaxonSet.subclass(*args_, **kwargs_) - else: - return TaxonSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_otu(self): return self.otu - def set_otu(self, otu): self.otu = otu - def export(self, outfile, level, namespace_='', name_='TaxonSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='TaxonSet') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="TaxonSet"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='TaxonSet'): - super(TaxonSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='TaxonSet') - if self.otu is not None and 'otu' not in already_processed: - already_processed.append('otu') - outfile.write(' otu=%s' % (self.gds_format_string(quote_attrib(self.otu).encode(ExternalEncoding), input_name='otu'), )) - def exportChildren(self, outfile, level, namespace_='', name_='TaxonSet', fromsubclass_=False): - super(TaxonSet, self).exportChildren(outfile, level, namespace_, name_, True) - def hasContent_(self): - if ( - super(TaxonSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='TaxonSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.otu is not None and 'otu' not in already_processed: - already_processed.append('otu') - showIndent(outfile, level) - outfile.write('otu = "%s",\n' % (self.otu,)) - super(TaxonSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(TaxonSet, self).exportLiteralChildren(outfile, level, name_) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('otu', node) - if value is not None and 'otu' not in already_processed: - already_processed.append('otu') - self.otu = value - super(TaxonSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - super(TaxonSet, self).buildChildren(child_, node, nodeName_, True) - pass -# end class TaxonSet - - -class NetworkNode(AbstractNode): - """A concrete network node implementation.""" - subclass = None - superclass = AbstractNode - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, root=False, valueOf_=None): - super(NetworkNode, self).__init__(about, meta, label, id, otu, root, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - def factory(*args_, **kwargs_): - if NetworkNode.subclass: - return NetworkNode.subclass(*args_, **kwargs_) - else: - return NetworkNode(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def export(self, outfile, level, namespace_='', name_='NetworkNode', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='NetworkNode') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='NetworkNode'): - super(NetworkNode, self).exportAttributes(outfile, level, already_processed, namespace_, name_='NetworkNode') - def exportChildren(self, outfile, level, namespace_='', name_='NetworkNode', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - def hasContent_(self): - if ( - self.meta or - super(NetworkNode, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='NetworkNode'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(NetworkNode, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(NetworkNode, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(NetworkNode, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) -# end class NetworkNode - - -class StandardMatrixObsRow(AbstractObsRow): - """This is a row in a matrix of standard data as granular obervations.""" - subclass = None - superclass = AbstractObsRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, cell=None, set=None, valueOf_=None): - super(StandardMatrixObsRow, self).__init__(about, meta, label, id, otu, cell, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if cell is None: - self.cell = [] - else: - self.cell = cell - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if StandardMatrixObsRow.subclass: - return StandardMatrixObsRow.subclass(*args_, **kwargs_) - else: - return StandardMatrixObsRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_cell(self): return self.cell - def set_cell(self, cell): self.cell = cell - def add_cell(self, value): self.cell.append(value) - def insert_cell(self, index, value): self.cell[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='StandardMatrixObsRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardMatrixObsRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardMatrixObsRow'): - super(StandardMatrixObsRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardMatrixObsRow') - def exportChildren(self, outfile, level, namespace_='', name_='StandardMatrixObsRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for cell_ in self.cell: - cell_.export(outfile, level, namespace_, name_='cell') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.cell or - self.set or - super(StandardMatrixObsRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardMatrixObsRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(StandardMatrixObsRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardMatrixObsRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('cell=[\n') - level += 1 - for cell_ in self.cell: - showIndent(outfile, level) - outfile.write('model_.StandardObs(\n') - cell_.exportLiteral(outfile, level, name_='StandardObs') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CellSet(\n') - set_.exportLiteral(outfile, level, name_='CellSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(StandardMatrixObsRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'cell': - obj_ = StandardObs.factory() - obj_.build(child_) - self.cell.append(obj_) - elif nodeName_ == 'set': - obj_ = CellSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class StandardMatrixObsRow - - -class StandardMatrixSeqRow(AbstractSeqRow): - """This is a row in a matrix of standard data as character sequences.""" - subclass = None - superclass = AbstractSeqRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, seq=None, valueOf_=None): - super(StandardMatrixSeqRow, self).__init__(about, meta, label, id, otu, seq, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.seq = seq - def factory(*args_, **kwargs_): - if StandardMatrixSeqRow.subclass: - return StandardMatrixSeqRow.subclass(*args_, **kwargs_) - else: - return StandardMatrixSeqRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_seq(self): return self.seq - def set_seq(self, seq): self.seq = seq - def validate_StandardSeq(self, value): - # Validate type StandardSeq, a restriction on AbstractTokenList. - pass - def export(self, outfile, level, namespace_='', name_='StandardMatrixSeqRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardMatrixSeqRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardMatrixSeqRow'): - super(StandardMatrixSeqRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardMatrixSeqRow') - def exportChildren(self, outfile, level, namespace_='', name_='StandardMatrixSeqRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('<%sseq>%s\n' % (namespace_, self.gds_format_double_list(self.seq, input_name='seq'), namespace_)) - def hasContent_(self): - if ( - self.meta or - self.seq is not None or - super(StandardMatrixSeqRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardMatrixSeqRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(StandardMatrixSeqRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardMatrixSeqRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('seq=%e,\n' % self.seq) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(StandardMatrixSeqRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'seq': - seq_ = child_.text - seq_ = self.gds_validate_double_list(seq_, node, 'seq') - self.seq = seq_ - self.validate_StandardSeq(self.seq) # validate type StandardSeq -# end class StandardMatrixSeqRow - - -class StandardUncertainStateSet(AbstractUncertainStateSet): - """The StandardUncertainStateSet type is a single uncertain ambiguity - mapping.""" - subclass = None - superclass = AbstractUncertainStateSet - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, member=None, valueOf_=None): - super(StandardUncertainStateSet, self).__init__(about, meta, label, id, symbol, member, ) - self.symbol = _cast(None, symbol) - if member is None: - self.member = [] - else: - self.member = member - def factory(*args_, **kwargs_): - if StandardUncertainStateSet.subclass: - return StandardUncertainStateSet.subclass(*args_, **kwargs_) - else: - return StandardUncertainStateSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_member(self): return self.member - def set_member(self, member): self.member = member - def add_member(self, value): self.member.append(value) - def insert_member(self, index, value): self.member[index] = value - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def export(self, outfile, level, namespace_='', name_='StandardUncertainStateSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardUncertainStateSet') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardUncertainStateSet'): - super(StandardUncertainStateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardUncertainStateSet') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (self.gds_format_string(quote_attrib(self.symbol).encode(ExternalEncoding), input_name='symbol'), )) - def exportChildren(self, outfile, level, namespace_='', name_='StandardUncertainStateSet', fromsubclass_=False): - for member_ in self.member: - member_.export(outfile, level, namespace_, name_='member') - def hasContent_(self): - if ( - self.member or - super(StandardUncertainStateSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardUncertainStateSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = "%s",\n' % (self.symbol,)) - super(StandardUncertainStateSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardUncertainStateSet, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('member=[\n') - level += 1 - for member_ in self.member: - showIndent(outfile, level) - outfile.write('model_.StandardMapping(\n') - member_.exportLiteral(outfile, level, name_='StandardMapping') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - self.symbol = value - super(StandardUncertainStateSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'member': - obj_ = StandardMapping.factory() - obj_.build(child_) - self.member.append(obj_) -# end class StandardUncertainStateSet - - -class RNAMatrixObsRow(AbstractObsRow): - """This is a row in a matrix of RNA data containing granular - observations.""" - subclass = None - superclass = AbstractObsRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, cell=None, set=None, valueOf_=None): - super(RNAMatrixObsRow, self).__init__(about, meta, label, id, otu, cell, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if cell is None: - self.cell = [] - else: - self.cell = cell - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if RNAMatrixObsRow.subclass: - return RNAMatrixObsRow.subclass(*args_, **kwargs_) - else: - return RNAMatrixObsRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_cell(self): return self.cell - def set_cell(self, cell): self.cell = cell - def add_cell(self, value): self.cell.append(value) - def insert_cell(self, index, value): self.cell[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='RNAMatrixObsRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNAMatrixObsRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNAMatrixObsRow'): - super(RNAMatrixObsRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNAMatrixObsRow') - def exportChildren(self, outfile, level, namespace_='', name_='RNAMatrixObsRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for cell_ in self.cell: - cell_.export(outfile, level, namespace_, name_='cell') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.cell or - self.set or - super(RNAMatrixObsRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNAMatrixObsRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RNAMatrixObsRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNAMatrixObsRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('cell=[\n') - level += 1 - for cell_ in self.cell: - showIndent(outfile, level) - outfile.write('model_.RNAObs(\n') - cell_.exportLiteral(outfile, level, name_='RNAObs') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CellSet(\n') - set_.exportLiteral(outfile, level, name_='CellSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RNAMatrixObsRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'cell': - obj_ = RNAObs.factory() - obj_.build(child_) - self.cell.append(obj_) - elif nodeName_ == 'set': - obj_ = CellSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class RNAMatrixObsRow - - -class RNAMatrixSeqRow(AbstractSeqRow): - """This is a row in a matrix of RNA data containing raw sequence data.""" - subclass = None - superclass = AbstractSeqRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, seq=None, valueOf_=None): - super(RNAMatrixSeqRow, self).__init__(about, meta, label, id, otu, seq, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.seq = seq - def factory(*args_, **kwargs_): - if RNAMatrixSeqRow.subclass: - return RNAMatrixSeqRow.subclass(*args_, **kwargs_) - else: - return RNAMatrixSeqRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_seq(self): return self.seq - def set_seq(self, seq): self.seq = seq - def validate_RNASeq(self, value): - # Validate type RNASeq, a restriction on AbstractSeq. - pass - def export(self, outfile, level, namespace_='', name_='RNAMatrixSeqRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNAMatrixSeqRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNAMatrixSeqRow'): - super(RNAMatrixSeqRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNAMatrixSeqRow') - def exportChildren(self, outfile, level, namespace_='', name_='RNAMatrixSeqRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('<%sseq>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.seq).encode(ExternalEncoding), input_name='seq'), namespace_)) - def hasContent_(self): - if ( - self.meta or - self.seq is not None or - super(RNAMatrixSeqRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNAMatrixSeqRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RNAMatrixSeqRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNAMatrixSeqRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('seq=%s,\n' % quote_python(self.seq).encode(ExternalEncoding)) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RNAMatrixSeqRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'seq': - seq_ = child_.text - seq_ = self.gds_validate_string(seq_, node, 'seq') - self.seq = seq_ - self.validate_RNASeq(self.seq) # validate type RNASeq -# end class RNAMatrixSeqRow - - -class RNAUncertainStateSet(AbstractUncertainStateSet): - """The RNAUncertainStateSet describes a single uncertain IUPAC - ambiguity mapping.""" - subclass = None - superclass = AbstractUncertainStateSet - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, member=None, valueOf_=None): - super(RNAUncertainStateSet, self).__init__(about, meta, label, id, symbol, member, ) - self.symbol = _cast(None, symbol) - if member is None: - self.member = [] - else: - self.member = member - def factory(*args_, **kwargs_): - if RNAUncertainStateSet.subclass: - return RNAUncertainStateSet.subclass(*args_, **kwargs_) - else: - return RNAUncertainStateSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_member(self): return self.member - def set_member(self, member): self.member = member - def add_member(self, value): self.member.append(value) - def insert_member(self, index, value): self.member[index] = value - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_RNAToken(self, value): - # Validate type RNAToken, a restriction on AbstractSymbol. - pass - def export(self, outfile, level, namespace_='', name_='RNAUncertainStateSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNAUncertainStateSet') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNAUncertainStateSet'): - super(RNAUncertainStateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNAUncertainStateSet') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='RNAUncertainStateSet', fromsubclass_=False): - for member_ in self.member: - member_.export(outfile, level, namespace_, name_='member') - def hasContent_(self): - if ( - self.member or - super(RNAUncertainStateSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNAUncertainStateSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = "%s",\n' % (self.symbol,)) - super(RNAUncertainStateSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNAUncertainStateSet, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('member=[\n') - level += 1 - for member_ in self.member: - showIndent(outfile, level) - outfile.write('model_.RNAMapping(\n') - member_.exportLiteral(outfile, level, name_='RNAMapping') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - self.symbol = value - self.validate_RNAToken(self.symbol) # validate type RNAToken - super(RNAUncertainStateSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'member': - obj_ = RNAMapping.factory() - obj_.build(child_) - self.member.append(obj_) -# end class RNAUncertainStateSet - - -class RestrictionMatrixObsRow(AbstractObsRow): - """This is a row in a matrix of restriction site data as granular - obervations.""" - subclass = None - superclass = AbstractObsRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, cell=None, set=None, valueOf_=None): - super(RestrictionMatrixObsRow, self).__init__(about, meta, label, id, otu, cell, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if cell is None: - self.cell = [] - else: - self.cell = cell - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if RestrictionMatrixObsRow.subclass: - return RestrictionMatrixObsRow.subclass(*args_, **kwargs_) - else: - return RestrictionMatrixObsRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_cell(self): return self.cell - def set_cell(self, cell): self.cell = cell - def add_cell(self, value): self.cell.append(value) - def insert_cell(self, index, value): self.cell[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='RestrictionMatrixObsRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionMatrixObsRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RestrictionMatrixObsRow'): - super(RestrictionMatrixObsRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionMatrixObsRow') - def exportChildren(self, outfile, level, namespace_='', name_='RestrictionMatrixObsRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for cell_ in self.cell: - cell_.export(outfile, level, namespace_, name_='cell') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.cell or - self.set or - super(RestrictionMatrixObsRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RestrictionMatrixObsRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RestrictionMatrixObsRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RestrictionMatrixObsRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('cell=[\n') - level += 1 - for cell_ in self.cell: - showIndent(outfile, level) - outfile.write('model_.RestrictionObs(\n') - cell_.exportLiteral(outfile, level, name_='RestrictionObs') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CellSet(\n') - set_.exportLiteral(outfile, level, name_='CellSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RestrictionMatrixObsRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'cell': - obj_ = RestrictionObs.factory() - obj_.build(child_) - self.cell.append(obj_) - elif nodeName_ == 'set': - obj_ = CellSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class RestrictionMatrixObsRow - - -class RestrictionMatrixSeqRow(AbstractSeqRow): - """This is a row in a matrix of restriction site data as character - sequences.""" - subclass = None - superclass = AbstractSeqRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, seq=None, valueOf_=None): - super(RestrictionMatrixSeqRow, self).__init__(about, meta, label, id, otu, seq, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.seq = seq - def factory(*args_, **kwargs_): - if RestrictionMatrixSeqRow.subclass: - return RestrictionMatrixSeqRow.subclass(*args_, **kwargs_) - else: - return RestrictionMatrixSeqRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_seq(self): return self.seq - def set_seq(self, seq): self.seq = seq - def validate_RestrictionSeq(self, value): - # Validate type RestrictionSeq, a restriction on xs:string. - pass - def export(self, outfile, level, namespace_='', name_='RestrictionMatrixSeqRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionMatrixSeqRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RestrictionMatrixSeqRow'): - super(RestrictionMatrixSeqRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionMatrixSeqRow') - def exportChildren(self, outfile, level, namespace_='', name_='RestrictionMatrixSeqRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('<%sseq>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.seq).encode(ExternalEncoding), input_name='seq'), namespace_)) - def hasContent_(self): - if ( - self.meta or - self.seq is not None or - super(RestrictionMatrixSeqRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RestrictionMatrixSeqRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RestrictionMatrixSeqRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RestrictionMatrixSeqRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('seq=%s,\n' % quote_python(self.seq).encode(ExternalEncoding)) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RestrictionMatrixSeqRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'seq': - seq_ = child_.text - seq_ = self.gds_validate_string(seq_, node, 'seq') - self.seq = seq_ - self.validate_RestrictionSeq(self.seq) # validate type RestrictionSeq -# end class RestrictionMatrixSeqRow - - -class AAMatrixObsRow(AbstractObsRow): - """This is a row in a matrix of amino acid data containing granular - observations.""" - subclass = None - superclass = AbstractObsRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, cell=None, set=None, valueOf_=None): - super(AAMatrixObsRow, self).__init__(about, meta, label, id, otu, cell, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if cell is None: - self.cell = [] - else: - self.cell = cell - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if AAMatrixObsRow.subclass: - return AAMatrixObsRow.subclass(*args_, **kwargs_) - else: - return AAMatrixObsRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_cell(self): return self.cell - def set_cell(self, cell): self.cell = cell - def add_cell(self, value): self.cell.append(value) - def insert_cell(self, index, value): self.cell[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='AAMatrixObsRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AAMatrixObsRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AAMatrixObsRow'): - super(AAMatrixObsRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AAMatrixObsRow') - def exportChildren(self, outfile, level, namespace_='', name_='AAMatrixObsRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for cell_ in self.cell: - cell_.export(outfile, level, namespace_, name_='cell') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.cell or - self.set or - super(AAMatrixObsRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AAMatrixObsRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AAMatrixObsRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AAMatrixObsRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('cell=[\n') - level += 1 - for cell_ in self.cell: - showIndent(outfile, level) - outfile.write('model_.AAObs(\n') - cell_.exportLiteral(outfile, level, name_='AAObs') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CellSet(\n') - set_.exportLiteral(outfile, level, name_='CellSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AAMatrixObsRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'cell': - obj_ = AAObs.factory() - obj_.build(child_) - self.cell.append(obj_) - elif nodeName_ == 'set': - obj_ = CellSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class AAMatrixObsRow - - -class AAMatrixSeqRow(AbstractSeqRow): - """This is a row in a matrix of amino acid data containing raw sequence - data.""" - subclass = None - superclass = AbstractSeqRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, seq=None, valueOf_=None): - super(AAMatrixSeqRow, self).__init__(about, meta, label, id, otu, seq, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.seq = seq - def factory(*args_, **kwargs_): - if AAMatrixSeqRow.subclass: - return AAMatrixSeqRow.subclass(*args_, **kwargs_) - else: - return AAMatrixSeqRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_seq(self): return self.seq - def set_seq(self, seq): self.seq = seq - def validate_AASeq(self, value): - # Validate type AASeq, a restriction on AbstractSeq. - pass - def export(self, outfile, level, namespace_='', name_='AAMatrixSeqRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AAMatrixSeqRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AAMatrixSeqRow'): - super(AAMatrixSeqRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AAMatrixSeqRow') - def exportChildren(self, outfile, level, namespace_='', name_='AAMatrixSeqRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('<%sseq>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.seq).encode(ExternalEncoding), input_name='seq'), namespace_)) - def hasContent_(self): - if ( - self.meta or - self.seq is not None or - super(AAMatrixSeqRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AAMatrixSeqRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AAMatrixSeqRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AAMatrixSeqRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('seq=%s,\n' % quote_python(self.seq).encode(ExternalEncoding)) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AAMatrixSeqRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'seq': - seq_ = child_.text - seq_ = self.gds_validate_string(seq_, node, 'seq') - self.seq = seq_ - self.validate_AASeq(self.seq) # validate type AASeq -# end class AAMatrixSeqRow - - -class AAUncertainStateSet(AbstractUncertainStateSet): - """The AAUncertainStateSet defines an uncertain ambiguity mapping.""" - subclass = None - superclass = AbstractUncertainStateSet - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, member=None, valueOf_=None): - super(AAUncertainStateSet, self).__init__(about, meta, label, id, symbol, member, ) - self.symbol = _cast(None, symbol) - if member is None: - self.member = [] - else: - self.member = member - def factory(*args_, **kwargs_): - if AAUncertainStateSet.subclass: - return AAUncertainStateSet.subclass(*args_, **kwargs_) - else: - return AAUncertainStateSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_member(self): return self.member - def set_member(self, member): self.member = member - def add_member(self, value): self.member.append(value) - def insert_member(self, index, value): self.member[index] = value - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_AAToken(self, value): - # Validate type AAToken, a restriction on AbstractSymbol. - pass - def export(self, outfile, level, namespace_='', name_='AAUncertainStateSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AAUncertainStateSet') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AAUncertainStateSet'): - super(AAUncertainStateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AAUncertainStateSet') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='AAUncertainStateSet', fromsubclass_=False): - for member_ in self.member: - member_.export(outfile, level, namespace_, name_='member') - def hasContent_(self): - if ( - self.member or - super(AAUncertainStateSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AAUncertainStateSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = "%s",\n' % (self.symbol,)) - super(AAUncertainStateSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AAUncertainStateSet, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('member=[\n') - level += 1 - for member_ in self.member: - showIndent(outfile, level) - outfile.write('model_.AAMapping(\n') - member_.exportLiteral(outfile, level, name_='AAMapping') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - self.symbol = value - self.validate_AAToken(self.symbol) # validate type AAToken - super(AAUncertainStateSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'member': - obj_ = AAMapping.factory() - obj_.build(child_) - self.member.append(obj_) -# end class AAUncertainStateSet - - -class DNAMatrixObsRow(AbstractObsRow): - """This is a row in a matrix of DNA data containing granular - observations.""" - subclass = None - superclass = AbstractObsRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, cell=None, set=None, valueOf_=None): - super(DNAMatrixObsRow, self).__init__(about, meta, label, id, otu, cell, set, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - if cell is None: - self.cell = [] - else: - self.cell = cell - if set is None: - self.set = [] - else: - self.set = set - def factory(*args_, **kwargs_): - if DNAMatrixObsRow.subclass: - return DNAMatrixObsRow.subclass(*args_, **kwargs_) - else: - return DNAMatrixObsRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_cell(self): return self.cell - def set_cell(self, cell): self.cell = cell - def add_cell(self, value): self.cell.append(value) - def insert_cell(self, index, value): self.cell[index] = value - def get_set(self): return self.set - def set_set(self, set): self.set = set - def add_set(self, value): self.set.append(value) - def insert_set(self, index, value): self.set[index] = value - def export(self, outfile, level, namespace_='', name_='DNAMatrixObsRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNAMatrixObsRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNAMatrixObsRow'): - super(DNAMatrixObsRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNAMatrixObsRow') - def exportChildren(self, outfile, level, namespace_='', name_='DNAMatrixObsRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - for cell_ in self.cell: - cell_.export(outfile, level, namespace_, name_='cell') - for set_ in self.set: - set_.export(outfile, level, namespace_, name_='set') - def hasContent_(self): - if ( - self.meta or - self.cell or - self.set or - super(DNAMatrixObsRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNAMatrixObsRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(DNAMatrixObsRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNAMatrixObsRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('cell=[\n') - level += 1 - for cell_ in self.cell: - showIndent(outfile, level) - outfile.write('model_.DNAObs(\n') - cell_.exportLiteral(outfile, level, name_='DNAObs') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('set=[\n') - level += 1 - for set_ in self.set: - showIndent(outfile, level) - outfile.write('model_.CellSet(\n') - set_.exportLiteral(outfile, level, name_='CellSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(DNAMatrixObsRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'cell': - obj_ = DNAObs.factory() - obj_.build(child_) - self.cell.append(obj_) - elif nodeName_ == 'set': - obj_ = CellSet.factory() - obj_.build(child_) - self.set.append(obj_) -# end class DNAMatrixObsRow - - -class DNAMatrixSeqRow(AbstractSeqRow): - """This is a row in a matrix of DNA data containing raw sequence data.""" - subclass = None - superclass = AbstractSeqRow - def __init__(self, about=None, meta=None, label=None, id=None, otu=None, seq=None, valueOf_=None): - super(DNAMatrixSeqRow, self).__init__(about, meta, label, id, otu, seq, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.seq = seq - def factory(*args_, **kwargs_): - if DNAMatrixSeqRow.subclass: - return DNAMatrixSeqRow.subclass(*args_, **kwargs_) - else: - return DNAMatrixSeqRow(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_seq(self): return self.seq - def set_seq(self, seq): self.seq = seq - def validate_DNASeq(self, value): - # Validate type DNASeq, a restriction on AbstractSeq. - pass - def export(self, outfile, level, namespace_='', name_='DNAMatrixSeqRow', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNAMatrixSeqRow') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNAMatrixSeqRow'): - super(DNAMatrixSeqRow, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNAMatrixSeqRow') - def exportChildren(self, outfile, level, namespace_='', name_='DNAMatrixSeqRow', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('<%sseq>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.seq).encode(ExternalEncoding), input_name='seq'), namespace_)) - def hasContent_(self): - if ( - self.meta or - self.seq is not None or - super(DNAMatrixSeqRow, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNAMatrixSeqRow'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(DNAMatrixSeqRow, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNAMatrixSeqRow, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.seq is not None: - showIndent(outfile, level) - outfile.write('seq=%s,\n' % quote_python(self.seq).encode(ExternalEncoding)) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(DNAMatrixSeqRow, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'seq': - seq_ = child_.text - seq_ = self.gds_validate_string(seq_, node, 'seq') - self.seq = seq_ - self.validate_DNASeq(self.seq) # validate type DNASeq -# end class DNAMatrixSeqRow - - -class DNAUncertainStateSet(AbstractUncertainStateSet): - """The DNAUncertainStateSet type defines an IUPAC ambiguity mapping. It - may enclose zero or more AbstractMapping elements to resolve - ambiguities.""" - subclass = None - superclass = AbstractUncertainStateSet - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, member=None, valueOf_=None): - super(DNAUncertainStateSet, self).__init__(about, meta, label, id, symbol, member, ) - self.symbol = _cast(None, symbol) - if member is None: - self.member = [] - else: - self.member = member - def factory(*args_, **kwargs_): - if DNAUncertainStateSet.subclass: - return DNAUncertainStateSet.subclass(*args_, **kwargs_) - else: - return DNAUncertainStateSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_member(self): return self.member - def set_member(self, member): self.member = member - def add_member(self, value): self.member.append(value) - def insert_member(self, index, value): self.member[index] = value - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_DNAToken(self, value): - # Validate type DNAToken, a restriction on AbstractSymbol. - pass - def export(self, outfile, level, namespace_='', name_='DNAUncertainStateSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNAUncertainStateSet') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNAUncertainStateSet'): - super(DNAUncertainStateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNAUncertainStateSet') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='DNAUncertainStateSet', fromsubclass_=False): - for member_ in self.member: - member_.export(outfile, level, namespace_, name_='member') - def hasContent_(self): - if ( - self.member or - super(DNAUncertainStateSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNAUncertainStateSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = "%s",\n' % (self.symbol,)) - super(DNAUncertainStateSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNAUncertainStateSet, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('member=[\n') - level += 1 - for member_ in self.member: - showIndent(outfile, level) - outfile.write('model_.DNAMapping(\n') - member_.exportLiteral(outfile, level, name_='DNAMapping') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - self.symbol = value - self.validate_DNAToken(self.symbol) # validate type DNAToken - super(DNAUncertainStateSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'member': - obj_ = DNAMapping.factory() - obj_.build(child_) - self.member.append(obj_) -# end class DNAUncertainStateSet - - -class AbstractCells(AbstractBlock): - """The AbstractSeqBlock type is the superclass for character blocks - that consist of granular character state observations.""" - subclass = None - superclass = AbstractBlock - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(AbstractCells, self).__init__(about, meta, label, id, otus, format, ) - self.matrix = matrix - def factory(*args_, **kwargs_): - if AbstractCells.subclass: - return AbstractCells.subclass(*args_, **kwargs_) - else: - return AbstractCells(*args_, **kwargs_) - factory = staticmethod(factory) - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='AbstractCells', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractCells') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractCells"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractCells'): - super(AbstractCells, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractCells') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractCells', fromsubclass_=False): - super(AbstractCells, self).exportChildren(outfile, level, namespace_, name_, True) - matrix_.export(outfile, level, namespace_, name_='matrix') - def hasContent_(self): - if ( - self.matrix is not None or - super(AbstractCells, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractCells'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractCells, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractCells, self).exportLiteralChildren(outfile, level, name_) - if self.AbstractObsMatrix is not None: - showIndent(outfile, level) - outfile.write('AbstractObsMatrix=model_.AbstractObsMatrix(\n') - self.AbstractObsMatrix.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractCells, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'matrix': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.set_matrix(obj_) - super(AbstractCells, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractCells - - -class AbstractSeqs(AbstractBlock): - """The AbstractSeqBlock type is the superclass for character blocks - that consist of raw character sequences.""" - subclass = None - superclass = AbstractBlock - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(AbstractSeqs, self).__init__(about, meta, label, id, otus, format, ) - self.matrix = matrix - def factory(*args_, **kwargs_): - if AbstractSeqs.subclass: - return AbstractSeqs.subclass(*args_, **kwargs_) - else: - return AbstractSeqs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='AbstractSeqs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractSeqs') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractSeqs"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractSeqs'): - super(AbstractSeqs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractSeqs') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractSeqs', fromsubclass_=False): - super(AbstractSeqs, self).exportChildren(outfile, level, namespace_, name_, True) - matrix_.export(outfile, level, namespace_, name_='matrix') - def hasContent_(self): - if ( - self.matrix is not None or - super(AbstractSeqs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractSeqs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractSeqs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractSeqs, self).exportLiteralChildren(outfile, level, name_) - if self.AbstractSeqMatrix is not None: - showIndent(outfile, level) - outfile.write('AbstractSeqMatrix=model_.AbstractSeqMatrix(\n') - self.AbstractSeqMatrix.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractSeqs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'matrix': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.set_matrix(obj_) - super(AbstractSeqs, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractSeqs - - -class AbstractPolymorphicStateSet(AbstractUncertainStateSet): - """The AbstractPolymorphicStateSet type is the super-class for a - polymorphic state set definition. The element has a required - AbstractSymbol attribute that in restricted concrete subclasses - must be of a sensible type such as a single IUPAC character. It - may enclose zero or more AbstractMapping elements to resolve - ambiguities.""" - subclass = None - superclass = AbstractUncertainStateSet - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, member=None, uncertain_state_set=None, valueOf_=None): - super(AbstractPolymorphicStateSet, self).__init__(about, meta, label, id, symbol, member, ) - if uncertain_state_set is None: - self.uncertain_state_set = [] - else: - self.uncertain_state_set = uncertain_state_set - def factory(*args_, **kwargs_): - if AbstractPolymorphicStateSet.subclass: - return AbstractPolymorphicStateSet.subclass(*args_, **kwargs_) - else: - return AbstractPolymorphicStateSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_uncertain_state_set(self): return self.uncertain_state_set - def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set - def add_uncertain_state_set(self, value): self.uncertain_state_set.append(value) - def insert_uncertain_state_set(self, index, value): self.uncertain_state_set[index] = value - def export(self, outfile, level, namespace_='', name_='AbstractPolymorphicStateSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractPolymorphicStateSet') - outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"') - if 'xsi:type' not in already_processed: - outfile.write(' xsi:type="AbstractPolymorphicStateSet"') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AbstractPolymorphicStateSet'): - super(AbstractPolymorphicStateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AbstractPolymorphicStateSet') - def exportChildren(self, outfile, level, namespace_='', name_='AbstractPolymorphicStateSet', fromsubclass_=False): - super(AbstractPolymorphicStateSet, self).exportChildren(outfile, level, namespace_, name_, True) - for uncertain_state_set_ in self.get_uncertain_state_set(): - uncertain_state_set_.export(outfile, level, namespace_, name_='uncertain_state_set') - def hasContent_(self): - if ( - self.uncertain_state_set or - super(AbstractPolymorphicStateSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AbstractPolymorphicStateSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(AbstractPolymorphicStateSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AbstractPolymorphicStateSet, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('uncertain_state_set=[\n') - level += 1 - for uncertain_state_set_ in self.uncertain_state_set: - showIndent(outfile, level) - outfile.write('model_.AbstractUncertainStateSet(\n') - uncertain_state_set_.exportLiteral(outfile, level, name_='AbstractUncertainStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(AbstractPolymorphicStateSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'uncertain_state_set': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.uncertain_state_set.append(obj_) - super(AbstractPolymorphicStateSet, self).buildChildren(child_, node, nodeName_, True) -# end class AbstractPolymorphicStateSet - - -class ContinuousCells(AbstractCells): - """A continuous characters block consisting of granular cells preceded - by metadata.""" - subclass = None - superclass = AbstractCells - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(ContinuousCells, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if ContinuousCells.subclass: - return ContinuousCells.subclass(*args_, **kwargs_) - else: - return ContinuousCells(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='ContinuousCells', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousCells') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ContinuousCells'): - super(ContinuousCells, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousCells') - def exportChildren(self, outfile, level, namespace_='', name_='ContinuousCells', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format', ) - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(ContinuousCells, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ContinuousCells'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(ContinuousCells, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ContinuousCells, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.ContinuousFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.ContinuousObsMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(ContinuousCells, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = ContinuousFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = ContinuousObsMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class ContinuousCells - - -class ContinuousSeqs(AbstractSeqs): - """A continuous characters block consisting of float sequences preceded - by metadata.""" - subclass = None - superclass = AbstractSeqs - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(ContinuousSeqs, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if ContinuousSeqs.subclass: - return ContinuousSeqs.subclass(*args_, **kwargs_) - else: - return ContinuousSeqs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='ContinuousSeqs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousSeqs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ContinuousSeqs'): - super(ContinuousSeqs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ContinuousSeqs') - def exportChildren(self, outfile, level, namespace_='', name_='ContinuousSeqs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format', ) - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(ContinuousSeqs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ContinuousSeqs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(ContinuousSeqs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ContinuousSeqs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.ContinuousFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.ContinuousSeqMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(ContinuousSeqs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = ContinuousFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = ContinuousSeqMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class ContinuousSeqs - - -class StandardCells(AbstractCells): - """A standard characters block consisting of granular cells preceded by - metadata.""" - subclass = None - superclass = AbstractCells - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(StandardCells, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if StandardCells.subclass: - return StandardCells.subclass(*args_, **kwargs_) - else: - return StandardCells(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='StandardCells', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardCells') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardCells'): - super(StandardCells, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardCells') - def exportChildren(self, outfile, level, namespace_='', name_='StandardCells', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format', ) - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(StandardCells, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardCells'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(StandardCells, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardCells, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.StandardFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.StandardObsMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(StandardCells, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = StandardFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = StandardObsMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class StandardCells - - -class StandardSeqs(AbstractSeqs): - """A standard characters block consisting of sequences preceded by - metadata.""" - subclass = None - superclass = AbstractSeqs - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(StandardSeqs, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if StandardSeqs.subclass: - return StandardSeqs.subclass(*args_, **kwargs_) - else: - return StandardSeqs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='StandardSeqs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardSeqs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardSeqs'): - super(StandardSeqs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardSeqs') - def exportChildren(self, outfile, level, namespace_='', name_='StandardSeqs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format', ) - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(StandardSeqs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardSeqs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(StandardSeqs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardSeqs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.StandardFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.StandardSeqMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(StandardSeqs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = StandardFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = StandardSeqMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class StandardSeqs - - -class StandardPolymorphicStateSet(AbstractPolymorphicStateSet): - """The StandardPolymorphicStateSet type is a single polymorphic - ambiguity mapping.""" - subclass = None - superclass = AbstractPolymorphicStateSet - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, member=None, uncertain_state_set=None, valueOf_=None): - super(StandardPolymorphicStateSet, self).__init__(about, meta, label, id, symbol, member, uncertain_state_set, ) - if member is None: - self.member = [] - else: - self.member = member - if uncertain_state_set is None: - self.uncertain_state_set = [] - else: - self.uncertain_state_set = uncertain_state_set - def factory(*args_, **kwargs_): - if StandardPolymorphicStateSet.subclass: - return StandardPolymorphicStateSet.subclass(*args_, **kwargs_) - else: - return StandardPolymorphicStateSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_member(self): return self.member - def set_member(self, member): self.member = member - def add_member(self, value): self.member.append(value) - def insert_member(self, index, value): self.member[index] = value - def get_uncertain_state_set(self): return self.uncertain_state_set - def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set - def add_uncertain_state_set(self, value): self.uncertain_state_set.append(value) - def insert_uncertain_state_set(self, index, value): self.uncertain_state_set[index] = value - def export(self, outfile, level, namespace_='', name_='StandardPolymorphicStateSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='StandardPolymorphicStateSet') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='StandardPolymorphicStateSet'): - super(StandardPolymorphicStateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='StandardPolymorphicStateSet') - def exportChildren(self, outfile, level, namespace_='', name_='StandardPolymorphicStateSet', fromsubclass_=False): - for member_ in self.member: - member_.export(outfile, level, namespace_, name_='member') - for uncertain_state_set_ in self.uncertain_state_set: - uncertain_state_set_.export(outfile, level, namespace_, name_='uncertain_state_set') - def hasContent_(self): - if ( - self.member or - self.uncertain_state_set or - super(StandardPolymorphicStateSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='StandardPolymorphicStateSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(StandardPolymorphicStateSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(StandardPolymorphicStateSet, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('member=[\n') - level += 1 - for member_ in self.member: - showIndent(outfile, level) - outfile.write('model_.StandardMapping(\n') - member_.exportLiteral(outfile, level, name_='StandardMapping') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('uncertain_state_set=[\n') - level += 1 - for uncertain_state_set_ in self.uncertain_state_set: - showIndent(outfile, level) - outfile.write('model_.StandardUncertainStateSet(\n') - uncertain_state_set_.exportLiteral(outfile, level, name_='StandardUncertainStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(StandardPolymorphicStateSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'member': - obj_ = StandardMapping.factory() - obj_.build(child_) - self.member.append(obj_) - elif nodeName_ == 'uncertain_state_set': - obj_ = StandardUncertainStateSet.factory() - obj_.build(child_) - self.uncertain_state_set.append(obj_) -# end class StandardPolymorphicStateSet - - -class RnaCells(AbstractCells): - """A RNA characters block consisting of granular cells preceded by - metadata.""" - subclass = None - superclass = AbstractCells - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(RnaCells, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if RnaCells.subclass: - return RnaCells.subclass(*args_, **kwargs_) - else: - return RnaCells(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='RnaCells', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RnaCells') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RnaCells'): - super(RnaCells, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RnaCells') - def exportChildren(self, outfile, level, namespace_='', name_='RnaCells', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format') - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(RnaCells, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RnaCells'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RnaCells, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RnaCells, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.RNAFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.RNAObsMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RnaCells, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = RNAFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = RNAObsMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class RnaCells - - -class RnaSeqs(AbstractSeqs): - """A RNA characters block consisting of sequences preceded by metadata.""" - subclass = None - superclass = AbstractSeqs - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(RnaSeqs, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if RnaSeqs.subclass: - return RnaSeqs.subclass(*args_, **kwargs_) - else: - return RnaSeqs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='RnaSeqs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RnaSeqs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RnaSeqs'): - super(RnaSeqs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RnaSeqs') - def exportChildren(self, outfile, level, namespace_='', name_='RnaSeqs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format', ) - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(RnaSeqs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RnaSeqs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RnaSeqs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RnaSeqs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.RNAFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.RNASeqMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RnaSeqs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = RNAFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = RNASeqMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class RnaSeqs - - -class RNAPolymorphicStateSet(AbstractPolymorphicStateSet): - """The RNAPolymorphicStateSet describes a single polymorphic IUPAC - ambiguity mapping.""" - subclass = None - superclass = AbstractPolymorphicStateSet - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, member=None, uncertain_state_set=None, valueOf_=None): - super(RNAPolymorphicStateSet, self).__init__(about, meta, label, id, symbol, member, uncertain_state_set, ) - self.symbol = _cast(None, symbol) - if member is None: - self.member = [] - else: - self.member = member - if uncertain_state_set is None: - self.uncertain_state_set = [] - else: - self.uncertain_state_set = uncertain_state_set - def factory(*args_, **kwargs_): - if RNAPolymorphicStateSet.subclass: - return RNAPolymorphicStateSet.subclass(*args_, **kwargs_) - else: - return RNAPolymorphicStateSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_member(self): return self.member - def set_member(self, member): self.member = member - def add_member(self, value): self.member.append(value) - def insert_member(self, index, value): self.member[index] = value - def get_uncertain_state_set(self): return self.uncertain_state_set - def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set - def add_uncertain_state_set(self, value): self.uncertain_state_set.append(value) - def insert_uncertain_state_set(self, index, value): self.uncertain_state_set[index] = value - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_RNAToken(self, value): - # Validate type RNAToken, a restriction on AbstractSymbol. - pass - def export(self, outfile, level, namespace_='', name_='RNAPolymorphicStateSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RNAPolymorphicStateSet') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RNAPolymorphicStateSet'): - super(RNAPolymorphicStateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RNAPolymorphicStateSet') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='RNAPolymorphicStateSet', fromsubclass_=False): - for member_ in self.member: - member_.export(outfile, level, namespace_, name_='member') - for uncertain_state_set_ in self.uncertain_state_set: - uncertain_state_set_.export(outfile, level, namespace_, name_='uncertain_state_set') - def hasContent_(self): - if ( - self.member or - self.uncertain_state_set or - super(RNAPolymorphicStateSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RNAPolymorphicStateSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = "%s",\n' % (self.symbol,)) - super(RNAPolymorphicStateSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RNAPolymorphicStateSet, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('member=[\n') - level += 1 - for member_ in self.member: - showIndent(outfile, level) - outfile.write('model_.RNAMapping(\n') - member_.exportLiteral(outfile, level, name_='RNAMapping') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('uncertain_state_set=[\n') - level += 1 - for uncertain_state_set_ in self.uncertain_state_set: - showIndent(outfile, level) - outfile.write('model_.RNAUncertainStateSet(\n') - uncertain_state_set_.exportLiteral(outfile, level, name_='RNAUncertainStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - self.symbol = value - self.validate_RNAToken(self.symbol) # validate type RNAToken - super(RNAPolymorphicStateSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'member': - obj_ = RNAMapping.factory() - obj_.build(child_) - self.member.append(obj_) - elif nodeName_ == 'uncertain_state_set': - obj_ = RNAUncertainStateSet.factory() - obj_.build(child_) - self.uncertain_state_set.append(obj_) -# end class RNAPolymorphicStateSet - - -class RestrictionCells(AbstractCells): - """A standard characters block consisting of granular cells preceded by - metadata.""" - subclass = None - superclass = AbstractCells - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(RestrictionCells, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if RestrictionCells.subclass: - return RestrictionCells.subclass(*args_, **kwargs_) - else: - return RestrictionCells(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='RestrictionCells', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionCells') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RestrictionCells'): - super(RestrictionCells, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionCells') - def exportChildren(self, outfile, level, namespace_='', name_='RestrictionCells', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format', ) - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(RestrictionCells, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RestrictionCells'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RestrictionCells, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RestrictionCells, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.RestrictionFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.RestrictionObsMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RestrictionCells, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = RestrictionFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = RestrictionObsMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class RestrictionCells - - -class RestrictionSeqs(AbstractSeqs): - """A restriction site characters block consisting of sequences preceded - by metadata.""" - subclass = None - superclass = AbstractSeqs - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(RestrictionSeqs, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if RestrictionSeqs.subclass: - return RestrictionSeqs.subclass(*args_, **kwargs_) - else: - return RestrictionSeqs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='RestrictionSeqs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionSeqs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='RestrictionSeqs'): - super(RestrictionSeqs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RestrictionSeqs') - def exportChildren(self, outfile, level, namespace_='', name_='RestrictionSeqs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format', ) - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(RestrictionSeqs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='RestrictionSeqs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(RestrictionSeqs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(RestrictionSeqs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.RestrictionFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.RestrictionSeqMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(RestrictionSeqs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = RestrictionFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = RestrictionSeqMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class RestrictionSeqs - - -class ProteinCells(AbstractCells): - """An amino acid characters block consisting of granular cells preceded - by metadata.""" - subclass = None - superclass = AbstractCells - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(ProteinCells, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if ProteinCells.subclass: - return ProteinCells.subclass(*args_, **kwargs_) - else: - return ProteinCells(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='ProteinCells', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ProteinCells') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ProteinCells'): - super(ProteinCells, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ProteinCells') - def exportChildren(self, outfile, level, namespace_='', name_='ProteinCells', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format', ) - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(ProteinCells, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ProteinCells'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(ProteinCells, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ProteinCells, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.AAFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.AAObsMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(ProteinCells, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = AAFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = AAObsMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class ProteinCells - - -class ProteinSeqs(AbstractSeqs): - """An amino acid characters block consisting of sequences preceded by - metadata.""" - subclass = None - superclass = AbstractSeqs - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(ProteinSeqs, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if ProteinSeqs.subclass: - return ProteinSeqs.subclass(*args_, **kwargs_) - else: - return ProteinSeqs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='ProteinSeqs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ProteinSeqs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ProteinSeqs'): - super(ProteinSeqs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ProteinSeqs') - def exportChildren(self, outfile, level, namespace_='', name_='ProteinSeqs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format', ) - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(ProteinSeqs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ProteinSeqs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(ProteinSeqs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(ProteinSeqs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.AAFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.AASeqMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(ProteinSeqs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = AAFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = AASeqMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class ProteinSeqs - - -class AAPolymorphicStateSet(AbstractPolymorphicStateSet): - """The AAPolymorphicStateSet defines a polymorphic ambiguity mapping.""" - subclass = None - superclass = AbstractPolymorphicStateSet - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, member=None, uncertain_state_set=None, valueOf_=None): - super(AAPolymorphicStateSet, self).__init__(about, meta, label, id, symbol, member, uncertain_state_set, ) - self.symbol = _cast(None, symbol) - if member is None: - self.member = [] - else: - self.member = member - if uncertain_state_set is None: - self.uncertain_state_set = [] - else: - self.uncertain_state_set = uncertain_state_set - def factory(*args_, **kwargs_): - if AAPolymorphicStateSet.subclass: - return AAPolymorphicStateSet.subclass(*args_, **kwargs_) - else: - return AAPolymorphicStateSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_member(self): return self.member - def set_member(self, member): self.member = member - def add_member(self, value): self.member.append(value) - def insert_member(self, index, value): self.member[index] = value - def get_uncertain_state_set(self): return self.uncertain_state_set - def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set - def add_uncertain_state_set(self, value): self.uncertain_state_set.append(value) - def insert_uncertain_state_set(self, index, value): self.uncertain_state_set[index] = value - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_AAToken(self, value): - # Validate type AAToken, a restriction on AbstractSymbol. - pass - def export(self, outfile, level, namespace_='', name_='AAPolymorphicStateSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='AAPolymorphicStateSet') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='AAPolymorphicStateSet'): - super(AAPolymorphicStateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AAPolymorphicStateSet') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='AAPolymorphicStateSet', fromsubclass_=False): - for member_ in self.member: - member_.export(outfile, level, namespace_, name_='member') - for uncertain_state_set_ in self.uncertain_state_set: - uncertain_state_set_.export(outfile, level, namespace_, name_='uncertain_state_set') - def hasContent_(self): - if ( - self.member or - self.uncertain_state_set or - super(AAPolymorphicStateSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='AAPolymorphicStateSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = "%s",\n' % (self.symbol,)) - super(AAPolymorphicStateSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(AAPolymorphicStateSet, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('member=[\n') - level += 1 - for member_ in self.member: - showIndent(outfile, level) - outfile.write('model_.AAMapping(\n') - member_.exportLiteral(outfile, level, name_='AAMapping') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('uncertain_state_set=[\n') - level += 1 - for uncertain_state_set_ in self.uncertain_state_set: - showIndent(outfile, level) - outfile.write('model_.AAUncertainStateSet(\n') - uncertain_state_set_.exportLiteral(outfile, level, name_='AAUncertainStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - self.symbol = value - self.validate_AAToken(self.symbol) # validate type AAToken - super(AAPolymorphicStateSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'member': - obj_ = AAMapping.factory() - obj_.build(child_) - self.member.append(obj_) - elif nodeName_ == 'uncertain_state_set': - obj_ = AAUncertainStateSet.factory() - obj_.build(child_) - self.uncertain_state_set.append(obj_) -# end class AAPolymorphicStateSet - - -class DnaCells(AbstractCells): - """A DNA characters block consisting of granular cells preceded by - metadata.""" - subclass = None - superclass = AbstractCells - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(DnaCells, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if DnaCells.subclass: - return DnaCells.subclass(*args_, **kwargs_) - else: - return DnaCells(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='DnaCells', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DnaCells') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DnaCells'): - super(DnaCells, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DnaCells') - def exportChildren(self, outfile, level, namespace_='', name_='DnaCells', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format', ) - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(DnaCells, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DnaCells'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(DnaCells, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DnaCells, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.DNAFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.DNAObsMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(DnaCells, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = DNAFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = DNAObsMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class DnaCells - - -class DnaSeqs(AbstractSeqs): - """A DNA characters block consisting of sequences preceded by metadata.""" - subclass = None - superclass = AbstractSeqs - def __init__(self, about=None, meta=None, label=None, id=None, otus=None, format=None, matrix=None, valueOf_=None): - super(DnaSeqs, self).__init__(about, meta, label, id, otus, format, matrix, ) - if meta is None: - self.meta = [] - else: - self.meta = meta - self.format = format - self.matrix = matrix - def factory(*args_, **kwargs_): - if DnaSeqs.subclass: - return DnaSeqs.subclass(*args_, **kwargs_) - else: - return DnaSeqs(*args_, **kwargs_) - factory = staticmethod(factory) - def get_meta(self): return self.meta - def set_meta(self, meta): self.meta = meta - def add_meta(self, value): self.meta.append(value) - def insert_meta(self, index, value): self.meta[index] = value - def get_format(self): return self.format - def set_format(self, format): self.format = format - def get_matrix(self): return self.matrix - def set_matrix(self, matrix): self.matrix = matrix - def export(self, outfile, level, namespace_='', name_='DnaSeqs', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DnaSeqs') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DnaSeqs'): - super(DnaSeqs, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DnaSeqs') - def exportChildren(self, outfile, level, namespace_='', name_='DnaSeqs', fromsubclass_=False): - for meta_ in self.get_meta(): - meta_.export(outfile, level, namespace_, name_='meta') - if self.format: - self.format.export(outfile, level, namespace_, name_='format', ) - if self.matrix: - self.matrix.export(outfile, level, namespace_, name_='matrix', ) - def hasContent_(self): - if ( - self.meta or - self.format is not None or - self.matrix is not None or - super(DnaSeqs, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DnaSeqs'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - super(DnaSeqs, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DnaSeqs, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('meta=[\n') - level += 1 - for meta_ in self.meta: - showIndent(outfile, level) - outfile.write('model_.Meta(\n') - meta_.exportLiteral(outfile, level, name_='Meta') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.format is not None: - showIndent(outfile, level) - outfile.write('format=model_.DNAFormat(\n') - self.format.exportLiteral(outfile, level, name_='format') - showIndent(outfile, level) - outfile.write('),\n') - if self.matrix is not None: - showIndent(outfile, level) - outfile.write('matrix=model_.DNASeqMatrix(\n') - self.matrix.exportLiteral(outfile, level, name_='matrix') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - super(DnaSeqs, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'meta': - type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if type_name_ is None: - type_name_ = child_.attrib.get('type') - if type_name_ is not None: - type_names_ = type_name_.split(':') - if len(type_names_) == 1: - type_name_ = type_names_[0] - else: - type_name_ = type_names_[1] - class_ = globals()[type_name_] - obj_ = class_.factory() - obj_.build(child_) - else: - raise NotImplementedError( - 'Class not implemented for element') - self.meta.append(obj_) - elif nodeName_ == 'format': - obj_ = DNAFormat.factory() - obj_.build(child_) - self.set_format(obj_) - elif nodeName_ == 'matrix': - obj_ = DNASeqMatrix.factory() - obj_.build(child_) - self.set_matrix(obj_) -# end class DnaSeqs - - -class DNAPolymorphicStateSet(AbstractPolymorphicStateSet): - """The DNAPolymorphicStateSet type defines an IUPAC ambiguity mapping. - It may enclose zero or more AbstractMapping elements to resolve - ambiguities.""" - subclass = None - superclass = AbstractPolymorphicStateSet - def __init__(self, about=None, meta=None, label=None, id=None, symbol=None, member=None, uncertain_state_set=None, valueOf_=None): - super(DNAPolymorphicStateSet, self).__init__(about, meta, label, id, symbol, member, uncertain_state_set, ) - self.symbol = _cast(None, symbol) - if member is None: - self.member = [] - else: - self.member = member - if uncertain_state_set is None: - self.uncertain_state_set = [] - else: - self.uncertain_state_set = uncertain_state_set - def factory(*args_, **kwargs_): - if DNAPolymorphicStateSet.subclass: - return DNAPolymorphicStateSet.subclass(*args_, **kwargs_) - else: - return DNAPolymorphicStateSet(*args_, **kwargs_) - factory = staticmethod(factory) - def get_member(self): return self.member - def set_member(self, member): self.member = member - def add_member(self, value): self.member.append(value) - def insert_member(self, index, value): self.member[index] = value - def get_uncertain_state_set(self): return self.uncertain_state_set - def set_uncertain_state_set(self, uncertain_state_set): self.uncertain_state_set = uncertain_state_set - def add_uncertain_state_set(self, value): self.uncertain_state_set.append(value) - def insert_uncertain_state_set(self, index, value): self.uncertain_state_set[index] = value - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_DNAToken(self, value): - # Validate type DNAToken, a restriction on AbstractSymbol. - pass - def export(self, outfile, level, namespace_='', name_='DNAPolymorphicStateSet', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DNAPolymorphicStateSet') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='DNAPolymorphicStateSet'): - super(DNAPolymorphicStateSet, self).exportAttributes(outfile, level, already_processed, namespace_, name_='DNAPolymorphicStateSet') - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - outfile.write(' symbol=%s' % (quote_attrib(self.symbol), )) - def exportChildren(self, outfile, level, namespace_='', name_='DNAPolymorphicStateSet', fromsubclass_=False): - for member_ in self.member: - member_.export(outfile, level, namespace_, name_='member') - for uncertain_state_set_ in self.uncertain_state_set: - uncertain_state_set_.export(outfile, level, namespace_, name_='uncertain_state_set') - def hasContent_(self): - if ( - self.member or - self.uncertain_state_set or - super(DNAPolymorphicStateSet, self).hasContent_() - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DNAPolymorphicStateSet'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.symbol is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - showIndent(outfile, level) - outfile.write('symbol = "%s",\n' % (self.symbol,)) - super(DNAPolymorphicStateSet, self).exportLiteralAttributes(outfile, level, already_processed, name_) - def exportLiteralChildren(self, outfile, level, name_): - super(DNAPolymorphicStateSet, self).exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('member=[\n') - level += 1 - for member_ in self.member: - showIndent(outfile, level) - outfile.write('model_.DNAMapping(\n') - member_.exportLiteral(outfile, level, name_='DNAMapping') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('uncertain_state_set=[\n') - level += 1 - for uncertain_state_set_ in self.uncertain_state_set: - showIndent(outfile, level) - outfile.write('model_.DNAUncertainStateSet(\n') - uncertain_state_set_.exportLiteral(outfile, level, name_='DNAUncertainStateSet') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('symbol', node) - if value is not None and 'symbol' not in already_processed: - already_processed.append('symbol') - self.symbol = value - self.validate_DNAToken(self.symbol) # validate type DNAToken - super(DNAPolymorphicStateSet, self).buildAttributes(node, attrs, already_processed) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'member': - obj_ = DNAMapping.factory() - obj_.build(child_) - self.member.append(obj_) - elif nodeName_ == 'uncertain_state_set': - obj_ = DNAUncertainStateSet.factory() - obj_.build(child_) - self.uncertain_state_set.append(obj_) -# end class DNAPolymorphicStateSet - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - -def usage(): - print USAGE_TEXT - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - rootClass = globals().get(tag) - return tag, rootClass - - -def parse(inFileName): - doc = parsexml_(inFileName) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'Nexml' - rootClass = Nexml - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## sys.stdout.write('\n') -## rootObj.export(sys.stdout, 0, name_=rootTag, -## namespacedef_='xmlns:nex="http://www.nexml.org/2009"') - return rootObj - - -def parseString(inString): - from StringIO import StringIO - doc = parsexml_(StringIO(inString)) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'Nexml' - rootClass = Nexml - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## sys.stdout.write('\n') -## rootObj.export(sys.stdout, 0, name_="Nexml", -## namespacedef_='xmlns:nex="http://www.nexml.org/2009"') - return rootObj - - -def parseLiteral(inFileName): - doc = parsexml_(inFileName) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'Nexml' - rootClass = Nexml - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## sys.stdout.write('#from nexml import *\n\n') -## sys.stdout.write('import nexml as model_\n\n') -## sys.stdout.write('rootObj = model_.rootTag(\n') -## rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) -## sys.stdout.write(')\n') - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - - -__all__ = [ - "AAChar", - "AAFormat", - "AAMapping", - "AAMatrixObsRow", - "AAMatrixSeqRow", - "AAObs", - "AAObsMatrix", - "AAPolymorphicStateSet", - "AASeqMatrix", - "AAState", - "AAStates", - "AAUncertainStateSet", - "AbstractBlock", - "AbstractCells", - "AbstractChar", - "AbstractEdge", - "AbstractFormat", - "AbstractMapping", - "AbstractNetwork", - "AbstractNode", - "AbstractObs", - "AbstractObsMatrix", - "AbstractObsRow", - "AbstractPolymorphicStateSet", - "AbstractRootEdge", - "AbstractSeqMatrix", - "AbstractSeqRow", - "AbstractSeqs", - "AbstractSet", - "AbstractState", - "AbstractStates", - "AbstractTree", - "AbstractTrees", - "AbstractUncertainStateSet", - "Annotated", - "Base", - "CellSet", - "CharSet", - "ContinuousCells", - "ContinuousChar", - "ContinuousFormat", - "ContinuousMatrixObsRow", - "ContinuousMatrixSeqRow", - "ContinuousObs", - "ContinuousObsMatrix", - "ContinuousSeqMatrix", - "ContinuousSeqs", - "DNAChar", - "DNAFormat", - "DNAMapping", - "DNAMatrixObsRow", - "DNAMatrixSeqRow", - "DNAObs", - "DNAObsMatrix", - "DNAPolymorphicStateSet", - "DNASeqMatrix", - "DNAState", - "DNAStates", - "DNAUncertainStateSet", - "DnaCells", - "DnaSeqs", - "FloatNetwork", - "FloatTree", - "IDTagged", - "IntNetwork", - "IntTree", - "Labelled", - "LiteralMeta", - "Meta", - "NetworkFloatEdge", - "NetworkIntEdge", - "NetworkNode", - "Nexml", - "NodeAndRootEdgeAndEdgeSet", - "OptionalTaxonLinked", - "ProteinCells", - "ProteinSeqs", - "RNAChar", - "RNAFormat", - "RNAMapping", - "RNAMatrixObsRow", - "RNAMatrixSeqRow", - "RNAObs", - "RNAObsMatrix", - "RNAPolymorphicStateSet", - "RNASeqMatrix", - "RNAState", - "RNAStates", - "RNAUncertainStateSet", - "ResourceMeta", - "RestrictionCells", - "RestrictionChar", - "RestrictionFormat", - "RestrictionMatrixObsRow", - "RestrictionMatrixSeqRow", - "RestrictionObs", - "RestrictionObsMatrix", - "RestrictionSeqMatrix", - "RestrictionSeqs", - "RestrictionState", - "RestrictionStates", - "RnaCells", - "RnaSeqs", - "RowSet", - "StandardCells", - "StandardChar", - "StandardFormat", - "StandardMapping", - "StandardMatrixObsRow", - "StandardMatrixSeqRow", - "StandardObs", - "StandardObsMatrix", - "StandardPolymorphicStateSet", - "StandardSeqMatrix", - "StandardSeqs", - "StandardState", - "StandardStates", - "StandardUncertainStateSet", - "StateSet", - "Taxa", - "TaxaLinked", - "Taxon", - "TaxonLinked", - "TaxonSet", - "TreeAndNetworkSet", - "TreeFloatEdge", - "TreeFloatRootEdge", - "TreeIntEdge", - "TreeIntRootEdge", - "TreeNode", - "Trees", - "attrExtensions" - ] diff --git a/ete2/nexml/_nexml.pyc b/ete2/nexml/_nexml.pyc deleted file mode 100644 index 7c70680..0000000 Binary files a/ete2/nexml/_nexml.pyc and /dev/null differ diff --git a/ete2/nexml/_nexml_tree.py b/ete2/nexml/_nexml_tree.py deleted file mode 100644 index 2a5985c..0000000 --- a/ete2/nexml/_nexml_tree.py +++ /dev/null @@ -1,196 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -import sys -from _nexml import MixedContainer, FloatTree, TreeFloatEdge, TreeNode, LiteralMeta -from ete2 import PhyloTree -from ete2.phylo.phylotree import _parse_species -from ete2.parser.newick import read_newick - -class Children(list): - def append(self, item): - list.append(self, item) - item.nexml_edge.source = self.node.nexml_node.id - item.nexml_edge.target = item.nexml_node.id - -class NexmlTree(PhyloTree): - """ - Special PhyloTree object with nexml support - """ - - def __repr__(self): - return "NexML ETE tree <%s>" %hex(hash(self)) - - def _get_dist(self): - return self.nexml_edge.get_length() - def _set_dist(self, value): - try: - self.nexml_edge.set_length(value) - except ValueError: - raise - - def _get_support(self): - return self._nexml_support.content - def _set_support(self, value): - try: - self._nexml_support.content = float(value) - except ValueError: - raise - - def _get_name(self): - return self.nexml_node.get_label() - - def _set_name(self, value): - try: - self.nexml_node.set_label(value) - except ValueError: - raise - - def _get_children(self): - return self._children - def _set_children(self, value): - if isinstance(value, Children) and \ - len(set([type(n)==type(self) for n in value]))<2: - self._children = value - else: - raise ValueError, "children:wrong type" - - dist = property(fget=_get_dist, fset=_set_dist) - support = property(fget=_get_support, fset=_set_support) - children = property(fget=_get_children, fset=_set_children) - name = property(fget=_get_name, fset=_set_name) - - def __init__(self, newick=None, alignment=None, alg_format="fasta", \ - sp_naming_function=_parse_species, format=0): - - self.nexml_tree = FloatTree() - self.nexml_tree.set_anyAttributes_({'xsi:type': 'FloatTree'}) - self.nexml_node = TreeNode() - self.nexml_edge = TreeFloatEdge() - self.nexml_node.id = "node_%s" %hash(self) - self.nexml_edge.id = "edge_%s" %hash(self) - self.nexml_project = None - self._nexml_support = LiteralMeta(datatype="float", property="branch_support", content=1.0) - self.nexml_edge.length = 0.0 - self.nexml_edge.add_meta(self._nexml_support) - - # Initialize empty PhyloTree - super(NexmlTree, self).__init__() - self._children = Children() - self._children.node = self - - if alignment: - self.link_to_alignment(alignment, alg_format) - if newick: - read_newick(newick, root_node=self, format=format) - self.set_species_naming_function(sp_naming_function) - - def set_nexml_project(self, nexml_obj): - self.nexml_project = nexml_obj - - def build(self, node): - self.nexml_tree = FloatTree() - tree = self.nexml_tree - tree.build(node) - - # This detects the outgroup of the tree even if the root tag - # is not set in any node - rootid = set([e.source for e in tree.edge]) - set([e.target for e in tree.edge]) - - nodeid2node = {rootid.pop(): self} - for xmledge in tree.edge: - child = nodeid2node.setdefault(xmledge.target, self.__class__() ) - parent = nodeid2node.setdefault(xmledge.source, self.__class__() ) - child.name = xmledge.target - child.nexml_node.id = xmledge.target - parent.name = xmledge.source - parent.nexml_node.id = xmledge.source - child.nexml_edge = xmledge - - if xmledge.length is not None: - child.dist = float(xmledge.length) - parent.add_child(child) - - for xmlnode in tree.node: - # just a warning. I don't know if this can occur - if xmlnode.id not in nodeid2node: - print >>sys.stderr, "Unused node", xmlnode.id - continue - - ete_node = nodeid2node[xmlnode.id] - ete_node.nexml_node = xmlnode - - if xmlnode.label: - ete_node.name = xmlnode.label - elif xmlnode.id is not None: - ete_node.name = xmlnode.id - - - def export(self, outfile=sys.stdout, level=0, namespace_='', name_='FloatTree', namespacedef_=''): - if self.nexml_tree: - info = [(n.nexml_edge, n.nexml_node) for n in self.traverse()] - self.nexml_node.set_root(True) - self.nexml_tree.set_edge([i[0] for i in info]) - self.nexml_tree.set_node([i[1] for i in info]) - self.nexml_tree.export(outfile=outfile, level=level, name_=name_, namespacedef_=namespacedef_) - - - def exportChildren(self, outfile, level, namespace_='', name_='FloatTree'): - sorted_nodes = [] - sorted_edges = [] - for n in self.traverse(): - # process node - node_obj = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'node', n.nexml_node) - sorted_nodes.append(node_obj) - - # process edge - if n.nexml_edge: - edge_obj = self.mixedclass_(MixedContainer.CategoryComplex, - MixedContainer.TypeNone, 'edge', n.nexml_edge) - sorted_edges.append(edge_obj) - - # process the nodes and edges - self.tree.content_ = sorted_nodes + sorted_edges - for item_ in self.tree.content_: - item_.export(outfile, level, item_.name, namespace_) - -# end class AbstractTreeSub -NexmlNode = NexmlTree diff --git a/ete2/nexml/_nexml_tree.pyc b/ete2/nexml/_nexml_tree.pyc deleted file mode 100644 index 2bfe37f..0000000 Binary files a/ete2/nexml/_nexml_tree.pyc and /dev/null differ diff --git a/ete2/orthoxml/__init__.py b/ete2/orthoxml/__init__.py deleted file mode 100644 index bbadad1..0000000 --- a/ete2/orthoxml/__init__.py +++ /dev/null @@ -1,41 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -from _orthoxml import * diff --git a/ete2/orthoxml/_orthoxml.py b/ete2/orthoxml/_orthoxml.py deleted file mode 100644 index bd0a848..0000000 --- a/ete2/orthoxml/_orthoxml.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Mon Jun 27 10:13:43 2011 by generateDS.py version 2.5b. -# - -import sys -import getopt -import re as re_ - -etree_ = None -Verbose_import_ = False -( XMLParser_import_none, XMLParser_import_lxml, - XMLParser_import_elementtree - ) = range(3) -XMLParser_import_library = None -try: - # lxml - from lxml import etree as etree_ - XMLParser_import_library = XMLParser_import_lxml - if Verbose_import_: - print("running with lxml.etree") -except ImportError: - try: - # cElementTree from Python 2.5+ - import xml.etree.cElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with cElementTree on Python 2.5+") - except ImportError: - try: - # ElementTree from Python 2.5+ - import xml.etree.ElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with ElementTree on Python 2.5+") - except ImportError: - try: - # normal cElementTree install - import cElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with cElementTree") - except ImportError: - try: - # normal ElementTree install - import elementtree.ElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with ElementTree") - except ImportError: - raise ImportError("Failed to import ElementTree from any known place") - -def parsexml_(*args, **kwargs): - if (XMLParser_import_library == XMLParser_import_lxml and - 'parser' not in kwargs): - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - kwargs['parser'] = etree_.ETCompatXMLParser() - doc = etree_.parse(*args, **kwargs) - return doc - -# -# User methods -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ImportError, exp: - - class GeneratedsSuper(object): - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_validate_string(self, input_data, node, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % input_data - def gds_validate_integer(self, input_data, node, input_name=''): - return input_data - def gds_format_integer_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_integer_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - try: - fvalue = float(value) - except (TypeError, ValueError), exp: - raise_parse_error(node, 'Requires sequence of integers') - return input_data - def gds_format_float(self, input_data, input_name=''): - return '%f' % input_data - def gds_validate_float(self, input_data, node, input_name=''): - return input_data - def gds_format_float_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_float_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - try: - fvalue = float(value) - except (TypeError, ValueError), exp: - raise_parse_error(node, 'Requires sequence of floats') - return input_data - def gds_format_double(self, input_data, input_name=''): - return '%e' % input_data - def gds_validate_double(self, input_data, node, input_name=''): - return input_data - def gds_format_double_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_double_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - try: - fvalue = float(value) - except (TypeError, ValueError), exp: - raise_parse_error(node, 'Requires sequence of doubles') - return input_data - def gds_format_boolean(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_boolean(self, input_data, node, input_name=''): - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_boolean_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - if value not in ('true', '1', 'false', '0', ): - raise_parse_error(node, 'Requires sequence of booleans ("true", "1", "false", "0")') - return input_data - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = 'utf-8' -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -STRING_CLEANUP_PAT = re_.compile(r"[\n\r\s]+") - -# -# Support/utility functions. -# - -def showIndent(outfile, level): - for idx in range(level): - outfile.write(' ') - -def quote_xml(inStr): - if not inStr: - return '' - s1 = (isinstance(inStr, basestring) and inStr or - '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - -def quote_attrib(inStr): - s1 = (isinstance(inStr, basestring) and inStr or - '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - -def find_attr_value_(attr_name, node): - attrs = node.attrib - # First try with no namespace. - value = attrs.get(attr_name) - if value is None: - # Now try the other possible namespaces. - namespaces = node.nsmap.itervalues() - for namespace in namespaces: - value = attrs.get('{%s}%s' % (namespace, attr_name, )) - if value is not None: - break - return value - - -class GDSParseError(Exception): - pass - -def raise_parse_error(node, msg): - if XMLParser_import_library == XMLParser_import_lxml: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - else: - msg = '%s (element %s)' % (msg, node.tag, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export(outfile, level, namespace,name) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % (self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % (self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % (self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % (self.name, self.value, self.name)) - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % \ - (self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0): - self.name = name - self.data_type = data_type - self.container = container - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - -class orthoXML(GeneratedsSuper): - """The OrthoXML root element. The source program/database of the file - for instance OMA or InParanoid. The version number of the file. - The version or release number of the source program/database at - time the file was generated.""" - subclass = None - superclass = None - def __init__(self, origin=None, version=None, originVersion=None, notes=None, species=None, scores=None, groups=None, valueOf_=None): - self.origin = _cast(None, origin) - self.version = _cast(float, version) - self.originVersion = _cast(None, originVersion) - self.notes = notes - if species is None: - self.species = [] - else: - self.species = species - self.scores = scores - self.groups = groups - def factory(*args_, **kwargs_): - if orthoXML.subclass: - return orthoXML.subclass(*args_, **kwargs_) - else: - return orthoXML(*args_, **kwargs_) - factory = staticmethod(factory) - def get_notes(self): return self.notes - def set_notes(self, notes): self.notes = notes - def get_species(self): return self.species - def set_species(self, species): self.species = species - def add_species(self, value): self.species.append(value) - def insert_species(self, index, value): self.species[index] = value - def get_scores(self): return self.scores - def set_scores(self, scores): self.scores = scores - def get_groups(self): return self.groups - def set_groups(self, groups): self.groups = groups - def get_origin(self): return self.origin - def set_origin(self, origin): self.origin = origin - def get_version(self): return self.version - def set_version(self, version): self.version = version - def get_originVersion(self): return self.originVersion - def set_originVersion(self, originVersion): self.originVersion = originVersion - def export(self, outfile, level, namespace_='ortho:', name_='orthoXML', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='orthoXML') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='orthoXML'): - if self.origin is not None and 'origin' not in already_processed: - already_processed.append('origin') - outfile.write(' origin=%s' % (self.gds_format_string(quote_attrib(self.origin).encode(ExternalEncoding), input_name='origin'), )) - if self.version is not None and 'version' not in already_processed: - already_processed.append('version') - outfile.write(' version="%s"' % self.gds_format_float(self.version, input_name='version')) - if self.originVersion is not None and 'originVersion' not in already_processed: - already_processed.append('originVersion') - outfile.write(' originVersion=%s' % (self.gds_format_string(quote_attrib(self.originVersion).encode(ExternalEncoding), input_name='originVersion'), )) - def exportChildren(self, outfile, level, namespace_='ortho:', name_='orthoXML', fromsubclass_=False): - if self.notes: - self.notes.export(outfile, level, namespace_, name_='notes') - for species_ in self.species: - species_.export(outfile, level, namespace_, name_='species') - if self.scores: - self.scores.export(outfile, level, namespace_, name_='scores') - if self.groups: - self.groups.export(outfile, level, namespace_, name_='groups', ) - def hasContent_(self): - if ( - self.notes is not None or - self.species or - self.scores is not None or - self.groups is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='orthoXML'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.origin is not None and 'origin' not in already_processed: - already_processed.append('origin') - showIndent(outfile, level) - outfile.write('origin = "%s",\n' % (self.origin,)) - if self.version is not None and 'version' not in already_processed: - already_processed.append('version') - showIndent(outfile, level) - outfile.write('version = %f,\n' % (self.version,)) - if self.originVersion is not None and 'originVersion' not in already_processed: - already_processed.append('originVersion') - showIndent(outfile, level) - outfile.write('originVersion = "%s",\n' % (self.originVersion,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.notes is not None: - showIndent(outfile, level) - outfile.write('notes=model_.notes(\n') - self.notes.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - showIndent(outfile, level) - outfile.write('species=[\n') - level += 1 - for species_ in self.species: - showIndent(outfile, level) - outfile.write('model_.species(\n') - species_.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.scores is not None: - showIndent(outfile, level) - outfile.write('scores=model_.scores(\n') - self.scores.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - if self.groups is not None: - showIndent(outfile, level) - outfile.write('groups=model_.groups(\n') - self.groups.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('origin', node) - if value is not None and 'origin' not in already_processed: - already_processed.append('origin') - self.origin = value - value = find_attr_value_('version', node) - if value is not None and 'version' not in already_processed: - already_processed.append('version') - try: - self.version = float(value) - except ValueError, exp: - raise ValueError('Bad float/double attribute (version): %s' % exp) - value = find_attr_value_('originVersion', node) - if value is not None and 'originVersion' not in already_processed: - already_processed.append('originVersion') - self.originVersion = value - self.originVersion = ' '.join(self.originVersion.split()) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'notes': - obj_ = notes.factory() - obj_.build(child_) - self.set_notes(obj_) - elif nodeName_ == 'species': - obj_ = species.factory() - obj_.build(child_) - self.species.append(obj_) - elif nodeName_ == 'scores': - obj_ = scores.factory() - obj_.build(child_) - self.set_scores(obj_) - elif nodeName_ == 'groups': - obj_ = groups.factory() - obj_.build(child_) - self.set_groups(obj_) -# end class orthoXML - - -class species(GeneratedsSuper): - """The species element contains all sequences of one species. The NCBI - Taxonomy identifier of the species to identify it unambiguously. - The name of the species.""" - subclass = None - superclass = None - def __init__(self, name=None, NCBITaxId=None, database=None, notes=None, valueOf_=None): - self.name = _cast(None, name) - self.NCBITaxId = _cast(int, NCBITaxId) - if database is None: - self.database = [] - else: - self.database = database - self.notes = notes - def factory(*args_, **kwargs_): - if species.subclass: - return species.subclass(*args_, **kwargs_) - else: - return species(*args_, **kwargs_) - factory = staticmethod(factory) - def get_database(self): return self.database - def set_database(self, database): self.database = database - def add_database(self, value): self.database.append(value) - def insert_database(self, index, value): self.database[index] = value - def get_notes(self): return self.notes - def set_notes(self, notes): self.notes = notes - def get_name(self): return self.name - def set_name(self, name): self.name = name - def get_NCBITaxId(self): return self.NCBITaxId - def set_NCBITaxId(self, NCBITaxId): self.NCBITaxId = NCBITaxId - def export(self, outfile, level, namespace_='ortho:', name_='species', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='species') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='species'): - if self.name is not None and 'name' not in already_processed: - already_processed.append('name') - outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) - if self.NCBITaxId is not None and 'NCBITaxId' not in already_processed: - already_processed.append('NCBITaxId') - outfile.write(' NCBITaxId="%s"' % self.gds_format_integer(self.NCBITaxId, input_name='NCBITaxId')) - def exportChildren(self, outfile, level, namespace_='ortho:', name_='species', fromsubclass_=False): - for database_ in self.database: - database_.export(outfile, level, namespace_, name_='database') - if self.notes: - self.notes.export(outfile, level, namespace_, name_='notes') - def hasContent_(self): - if ( - self.database or - self.notes is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='species'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.name is not None and 'name' not in already_processed: - already_processed.append('name') - showIndent(outfile, level) - outfile.write('name = "%s",\n' % (self.name,)) - if self.NCBITaxId is not None and 'NCBITaxId' not in already_processed: - already_processed.append('NCBITaxId') - showIndent(outfile, level) - outfile.write('NCBITaxId = %d,\n' % (self.NCBITaxId,)) - def exportLiteralChildren(self, outfile, level, name_): - showIndent(outfile, level) - outfile.write('database=[\n') - level += 1 - for database_ in self.database: - showIndent(outfile, level) - outfile.write('model_.database(\n') - database_.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.notes is not None: - showIndent(outfile, level) - outfile.write('notes=model_.notes(\n') - self.notes.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('name', node) - if value is not None and 'name' not in already_processed: - already_processed.append('name') - self.name = value - value = find_attr_value_('NCBITaxId', node) - if value is not None and 'NCBITaxId' not in already_processed: - already_processed.append('NCBITaxId') - try: - self.NCBITaxId = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'database': - obj_ = database.factory() - obj_.build(child_) - self.database.append(obj_) - elif nodeName_ == 'notes': - obj_ = notes.factory() - obj_.build(child_) - self.set_notes(obj_) -# end class species - - -class database(GeneratedsSuper): - """A database element contains all genes from a single database/source. - A Uniform Resource Identifier (URI) pointing to the gene. In the - simplest case one could imagine a URL which in concatenation - with the gene identifier links to the website of the gene in the - source database. However, how this is used depends on the source - of the orthoXML file. Name of the database. A Uniform Resource - Identifier (URI) pointing to the protein. A Uniform Resource - Identifier (URI) pointing to the transcript. Version number of - the database.""" - subclass = None - superclass = None - def __init__(self, transcriptLink=None, protLink=None, geneLink=None, name=None, version=None, genes=None, valueOf_=None): - self.transcriptLink = _cast(None, transcriptLink) - self.protLink = _cast(None, protLink) - self.geneLink = _cast(None, geneLink) - self.name = _cast(None, name) - self.version = _cast(None, version) - self.genes = genes - def factory(*args_, **kwargs_): - if database.subclass: - return database.subclass(*args_, **kwargs_) - else: - return database(*args_, **kwargs_) - factory = staticmethod(factory) - def get_genes(self): return self.genes - def set_genes(self, genes): self.genes = genes - def get_transcriptLink(self): return self.transcriptLink - def set_transcriptLink(self, transcriptLink): self.transcriptLink = transcriptLink - def get_protLink(self): return self.protLink - def set_protLink(self, protLink): self.protLink = protLink - def get_geneLink(self): return self.geneLink - def set_geneLink(self, geneLink): self.geneLink = geneLink - def get_name(self): return self.name - def set_name(self, name): self.name = name - def get_version(self): return self.version - def set_version(self, version): self.version = version - def export(self, outfile, level, namespace_='ortho:', name_='database', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='database') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='database'): - if self.transcriptLink is not None and 'transcriptLink' not in already_processed: - already_processed.append('transcriptLink') - outfile.write(' transcriptLink=%s' % (self.gds_format_string(quote_attrib(self.transcriptLink).encode(ExternalEncoding), input_name='transcriptLink'), )) - if self.protLink is not None and 'protLink' not in already_processed: - already_processed.append('protLink') - outfile.write(' protLink=%s' % (self.gds_format_string(quote_attrib(self.protLink).encode(ExternalEncoding), input_name='protLink'), )) - if self.geneLink is not None and 'geneLink' not in already_processed: - already_processed.append('geneLink') - outfile.write(' geneLink=%s' % (self.gds_format_string(quote_attrib(self.geneLink).encode(ExternalEncoding), input_name='geneLink'), )) - if self.name is not None and 'name' not in already_processed: - already_processed.append('name') - outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) - if self.version is not None and 'version' not in already_processed: - already_processed.append('version') - outfile.write(' version=%s' % (self.gds_format_string(quote_attrib(self.version).encode(ExternalEncoding), input_name='version'), )) - def exportChildren(self, outfile, level, namespace_='ortho:', name_='database', fromsubclass_=False): - if self.genes: - self.genes.export(outfile, level, namespace_, name_='genes', ) - def hasContent_(self): - if ( - self.genes is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='database'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.transcriptLink is not None and 'transcriptLink' not in already_processed: - already_processed.append('transcriptLink') - showIndent(outfile, level) - outfile.write('transcriptLink = "%s",\n' % (self.transcriptLink,)) - if self.protLink is not None and 'protLink' not in already_processed: - already_processed.append('protLink') - showIndent(outfile, level) - outfile.write('protLink = "%s",\n' % (self.protLink,)) - if self.geneLink is not None and 'geneLink' not in already_processed: - already_processed.append('geneLink') - showIndent(outfile, level) - outfile.write('geneLink = "%s",\n' % (self.geneLink,)) - if self.name is not None and 'name' not in already_processed: - already_processed.append('name') - showIndent(outfile, level) - outfile.write('name = "%s",\n' % (self.name,)) - if self.version is not None and 'version' not in already_processed: - already_processed.append('version') - showIndent(outfile, level) - outfile.write('version = "%s",\n' % (self.version,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.genes is not None: - showIndent(outfile, level) - outfile.write('genes=model_.genes(\n') - self.genes.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('transcriptLink', node) - if value is not None and 'transcriptLink' not in already_processed: - already_processed.append('transcriptLink') - self.transcriptLink = value - value = find_attr_value_('protLink', node) - if value is not None and 'protLink' not in already_processed: - already_processed.append('protLink') - self.protLink = value - value = find_attr_value_('geneLink', node) - if value is not None and 'geneLink' not in already_processed: - already_processed.append('geneLink') - self.geneLink = value - value = find_attr_value_('name', node) - if value is not None and 'name' not in already_processed: - already_processed.append('name') - self.name = value - value = find_attr_value_('version', node) - if value is not None and 'version' not in already_processed: - already_processed.append('version') - self.version = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'genes': - obj_ = genes.factory() - obj_.build(child_) - self.set_genes(obj_) -# end class database - - -class genes(GeneratedsSuper): - """A gene element represents a list of genes.""" - subclass = None - superclass = None - def __init__(self, gene=None, valueOf_=None): - if gene is None: - self.gene = [] - else: - self.gene = gene - def factory(*args_, **kwargs_): - if genes.subclass: - return genes.subclass(*args_, **kwargs_) - else: - return genes(*args_, **kwargs_) - factory = staticmethod(factory) - def get_gene(self): return self.gene - def set_gene(self, gene): self.gene = gene - def add_gene(self, value): self.gene.append(value) - def insert_gene(self, index, value): self.gene[index] = value - def export(self, outfile, level, namespace_='ortho:', name_='genes', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='genes') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='genes'): - pass - def exportChildren(self, outfile, level, namespace_='ortho:', name_='genes', fromsubclass_=False): - for gene_ in self.gene: - gene_.export(outfile, level, namespace_, name_='gene') - def hasContent_(self): - if ( - self.gene - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='genes'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - pass - def exportLiteralChildren(self, outfile, level, name_): - showIndent(outfile, level) - outfile.write('gene=[\n') - level += 1 - for gene_ in self.gene: - showIndent(outfile, level) - outfile.write('model_.gene(\n') - gene_.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'gene': - obj_ = gene.factory() - obj_.build(child_) - self.gene.append(obj_) -# end class genes - - -class gene(GeneratedsSuper): - """The gene element represents a single gene, protein or transcript. It - is in fact a set of identifiers: one internal identifier that is - used to link from geneRef elements in ortholog clusters and gene - identifiers, transcript identifiers and protein identifiers to - identify the molecule. The proper term for this element would - therefore rather be molecule. However, as the general purpose of - orthoXML is to represent orthology data for genes the term gene - is used instead. Gene, protein and transcipt identifiers are - optional but at least one of the three should be given. The - source database of the gene is defined through the database - element in which the gene element lies and the identifiers - should stem from this source. Identifier of the gene in the - source database. Multiple splice forms are possible by having - the same geneId more than once. Internal identifier to link to - the gene via the geneRef elements. Identifier of the protein in - the source database. Identifier of the transcript in the source - database.""" - subclass = None - superclass = None - def __init__(self, protId=None, id=None, geneId=None, transcriptId=None, valueOf_=None): - self.protId = _cast(None, protId) - self.id = _cast(int, id) - self.geneId = _cast(None, geneId) - self.transcriptId = _cast(None, transcriptId) - pass - def factory(*args_, **kwargs_): - if gene.subclass: - return gene.subclass(*args_, **kwargs_) - else: - return gene(*args_, **kwargs_) - factory = staticmethod(factory) - def get_protId(self): return self.protId - def set_protId(self, protId): self.protId = protId - def get_id(self): return self.id - def set_id(self, id): self.id = id - def get_geneId(self): return self.geneId - def set_geneId(self, geneId): self.geneId = geneId - def get_transcriptId(self): return self.transcriptId - def set_transcriptId(self, transcriptId): self.transcriptId = transcriptId - def export(self, outfile, level, namespace_='ortho:', name_='gene', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='gene') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='gene'): - if self.protId is not None and 'protId' not in already_processed: - already_processed.append('protId') - outfile.write(' protId=%s' % (self.gds_format_string(quote_attrib(self.protId).encode(ExternalEncoding), input_name='protId'), )) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id="%s"' % self.gds_format_integer(self.id, input_name='id')) - if self.geneId is not None and 'geneId' not in already_processed: - already_processed.append('geneId') - outfile.write(' geneId=%s' % (self.gds_format_string(quote_attrib(self.geneId).encode(ExternalEncoding), input_name='geneId'), )) - if self.transcriptId is not None and 'transcriptId' not in already_processed: - already_processed.append('transcriptId') - outfile.write(' transcriptId=%s' % (self.gds_format_string(quote_attrib(self.transcriptId).encode(ExternalEncoding), input_name='transcriptId'), )) - def exportChildren(self, outfile, level, namespace_='ortho:', name_='gene', fromsubclass_=False): - pass - def hasContent_(self): - if ( - - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='gene'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.protId is not None and 'protId' not in already_processed: - already_processed.append('protId') - showIndent(outfile, level) - outfile.write('protId = "%s",\n' % (self.protId,)) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = %d,\n' % (self.id,)) - if self.geneId is not None and 'geneId' not in already_processed: - already_processed.append('geneId') - showIndent(outfile, level) - outfile.write('geneId = "%s",\n' % (self.geneId,)) - if self.transcriptId is not None and 'transcriptId' not in already_processed: - already_processed.append('transcriptId') - showIndent(outfile, level) - outfile.write('transcriptId = "%s",\n' % (self.transcriptId,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('protId', node) - if value is not None and 'protId' not in already_processed: - already_processed.append('protId') - self.protId = value - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - try: - self.id = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - value = find_attr_value_('geneId', node) - if value is not None and 'geneId' not in already_processed: - already_processed.append('geneId') - self.geneId = value - value = find_attr_value_('transcriptId', node) - if value is not None and 'transcriptId' not in already_processed: - already_processed.append('transcriptId') - self.transcriptId = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class gene - - -class scores(GeneratedsSuper): - """A list of score definitions.""" - subclass = None - superclass = None - def __init__(self, scoreDef=None, valueOf_=None): - if scoreDef is None: - self.scoreDef = [] - else: - self.scoreDef = scoreDef - def factory(*args_, **kwargs_): - if scores.subclass: - return scores.subclass(*args_, **kwargs_) - else: - return scores(*args_, **kwargs_) - factory = staticmethod(factory) - def get_scoreDef(self): return self.scoreDef - def set_scoreDef(self, scoreDef): self.scoreDef = scoreDef - def add_scoreDef(self, value): self.scoreDef.append(value) - def insert_scoreDef(self, index, value): self.scoreDef[index] = value - def export(self, outfile, level, namespace_='ortho:', name_='scores', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='scores') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='scores'): - pass - def exportChildren(self, outfile, level, namespace_='ortho:', name_='scores', fromsubclass_=False): - for scoreDef_ in self.scoreDef: - scoreDef_.export(outfile, level, namespace_, name_='scoreDef') - def hasContent_(self): - if ( - self.scoreDef - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='scores'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - pass - def exportLiteralChildren(self, outfile, level, name_): - showIndent(outfile, level) - outfile.write('scoreDef=[\n') - level += 1 - for scoreDef_ in self.scoreDef: - showIndent(outfile, level) - outfile.write('model_.scoreDef(\n') - scoreDef_.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'scoreDef': - obj_ = scoreDef.factory() - obj_.build(child_) - self.scoreDef.append(obj_) -# end class scores - - -class groups(GeneratedsSuper): - """Represents the list of ortholog groups. Note that the purpose of - OrthoXML is to store orthology assignment hence on the top level - only ortholog groups are allowed.""" - subclass = None - superclass = None - def __init__(self, orthologGroup=None, valueOf_=None): - if orthologGroup is None: - self.orthologGroup = [] - else: - self.orthologGroup = orthologGroup - def factory(*args_, **kwargs_): - if groups.subclass: - return groups.subclass(*args_, **kwargs_) - else: - return groups(*args_, **kwargs_) - factory = staticmethod(factory) - def get_orthologGroup(self): return self.orthologGroup - def set_orthologGroup(self, orthologGroup): self.orthologGroup = orthologGroup - def add_orthologGroup(self, value): self.orthologGroup.append(value) - def insert_orthologGroup(self, index, value): self.orthologGroup[index] = value - def export(self, outfile, level, namespace_='ortho:', name_='groups', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='groups') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='groups'): - pass - def exportChildren(self, outfile, level, namespace_='ortho:', name_='groups', fromsubclass_=False): - for orthologGroup_ in self.orthologGroup: - orthologGroup_.export(outfile, level, namespace_, name_='orthologGroup') - def hasContent_(self): - if ( - self.orthologGroup - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='groups'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - pass - def exportLiteralChildren(self, outfile, level, name_): - showIndent(outfile, level) - outfile.write('orthologGroup=[\n') - level += 1 - for orthologGroup_ in self.orthologGroup: - showIndent(outfile, level) - outfile.write('model_.group(\n') - orthologGroup_.exportLiteral(outfile, level, name_='group') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'orthologGroup': - obj_ = group.factory() - obj_.build(child_) - self.orthologGroup.append(obj_) -# end class groups - - -class group(GeneratedsSuper): - """A group of genes or nested groups. In case of a orothologGroup - element, all genes in the group or in the nested groups are - orthologs to each other i.e. stem from the same gene in the last - common ancester of the species. In case of a paralogGroup the - genes are paralogs to each other. Subgroups within the group - allow the represention of phylogenetic trees. For more details - and examples see http://orthoxml.org/orthoxml_doc.html. A group - can may contain two or more of the three alternatives geneRef, - paralogGroup, and orthologGroup. By combining these, complex - phylogenies are possible. Identifier for the group in context of - the resource. This attribute is not required but if your - resource provides identifiers for the ortholog groups we - strongly recommend to use it at least for the top level groups.""" - subclass = None - superclass = None - def __init__(self, id=None, score=None, property=None, geneRef=None, paralogGroup=None, orthologGroup=None, notes=None, valueOf_=None): - self.id = _cast(None, id) - if score is None: - self.score = [] - else: - self.score = score - if property is None: - self.property = [] - else: - self.property = property - if geneRef is None: - self.geneRef = [] - else: - self.geneRef = geneRef - if paralogGroup is None: - self.paralogGroup = [] - else: - self.paralogGroup = paralogGroup - if orthologGroup is None: - self.orthologGroup = [] - else: - self.orthologGroup = orthologGroup - self.notes = notes - def factory(*args_, **kwargs_): - if group.subclass: - return group.subclass(*args_, **kwargs_) - else: - return group(*args_, **kwargs_) - factory = staticmethod(factory) - def get_score(self): return self.score - def set_score(self, score): self.score = score - def add_score(self, value): self.score.append(value) - def insert_score(self, index, value): self.score[index] = value - def get_property(self): return self.property - def set_property(self, property): self.property = property - def add_property(self, value): self.property.append(value) - def insert_property(self, index, value): self.property[index] = value - def get_geneRef(self): return self.geneRef - def set_geneRef(self, geneRef): self.geneRef = geneRef - def add_geneRef(self, value): self.geneRef.append(value) - def insert_geneRef(self, index, value): self.geneRef[index] = value - def get_paralogGroup(self): return self.paralogGroup - def set_paralogGroup(self, paralogGroup): self.paralogGroup = paralogGroup - def add_paralogGroup(self, value): self.paralogGroup.append(value) - def insert_paralogGroup(self, index, value): self.paralogGroup[index] = value - def get_orthologGroup(self): return self.orthologGroup - def set_orthologGroup(self, orthologGroup): self.orthologGroup = orthologGroup - def add_orthologGroup(self, value): self.orthologGroup.append(value) - def insert_orthologGroup(self, index, value): self.orthologGroup[index] = value - def get_notes(self): return self.notes - def set_notes(self, notes): self.notes = notes - def get_id(self): return self.id - def set_id(self, id): self.id = id - def export(self, outfile, level, namespace_='ortho:', name_='group', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='group') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='group'): - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) - def exportChildren(self, outfile, level, namespace_='ortho:', name_='group', fromsubclass_=False): - for score_ in self.score: - score_.export(outfile, level, namespace_, name_='score') - for property_ in self.property: - property_.export(outfile, level, namespace_, name_='property') - for geneRef_ in self.geneRef: - geneRef_.export(outfile, level, namespace_, name_='geneRef') - for paralogGroup_ in self.paralogGroup: - paralogGroup_.export(outfile, level, namespace_, name_='paralogGroup') - for orthologGroup_ in self.orthologGroup: - orthologGroup_.export(outfile, level, namespace_, name_='orthologGroup') - if self.notes: - self.notes.export(outfile, level, namespace_, name_='notes') - def hasContent_(self): - if ( - self.score or - self.property or - self.geneRef or - self.paralogGroup or - self.orthologGroup or - self.notes is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='group'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = "%s",\n' % (self.id,)) - def exportLiteralChildren(self, outfile, level, name_): - showIndent(outfile, level) - outfile.write('score=[\n') - level += 1 - for score_ in self.score: - showIndent(outfile, level) - outfile.write('model_.score(\n') - score_.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('property=[\n') - level += 1 - for property_ in self.property: - showIndent(outfile, level) - outfile.write('model_.property(\n') - property_.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('geneRef=[\n') - level += 1 - for geneRef_ in self.geneRef: - showIndent(outfile, level) - outfile.write('model_.geneRef(\n') - geneRef_.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('paralogGroup=[\n') - level += 1 - for paralogGroup_ in self.paralogGroup: - showIndent(outfile, level) - outfile.write('model_.group(\n') - paralogGroup_.exportLiteral(outfile, level, name_='group') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('orthologGroup=[\n') - level += 1 - for orthologGroup_ in self.orthologGroup: - showIndent(outfile, level) - outfile.write('model_.group(\n') - orthologGroup_.exportLiteral(outfile, level, name_='group') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.notes is not None: - showIndent(outfile, level) - outfile.write('notes=model_.notes(\n') - self.notes.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - self.id = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'score': - obj_ = score.factory() - obj_.build(child_) - self.score.append(obj_) - elif nodeName_ == 'property': - obj_ = property.factory() - obj_.build(child_) - self.property.append(obj_) - elif nodeName_ == 'geneRef': - obj_ = geneRef.factory() - obj_.build(child_) - self.geneRef.append(obj_) - elif nodeName_ == 'paralogGroup': - obj_ = group.factory() - obj_.build(child_) - self.paralogGroup.append(obj_) - elif nodeName_ == 'orthologGroup': - obj_ = group.factory() - obj_.build(child_) - self.orthologGroup.append(obj_) - elif nodeName_ == 'notes': - obj_ = notes.factory() - obj_.build(child_) - self.set_notes(obj_) -# end class group - - -class geneRef(GeneratedsSuper): - """The geneRef element is a link to the gene definition under the - species element. It defines the members of an ortholog or - paralog group. The same gene can be referenced muliple times. - The geneRef element can have multiple score elements and a notes - elements as children. The notes element can for instance be used - for special, ortholog-database-specific information (with - InParanoid, for example, we could use it to mark the seed - orthologs). Internal identifier for a gene element defined under - the species element.""" - subclass = None - superclass = None - def __init__(self, id=None, score=None, notes=None, valueOf_=None): - self.id = _cast(int, id) - if score is None: - self.score = [] - else: - self.score = score - self.notes = notes - def factory(*args_, **kwargs_): - if geneRef.subclass: - return geneRef.subclass(*args_, **kwargs_) - else: - return geneRef(*args_, **kwargs_) - factory = staticmethod(factory) - def get_score(self): return self.score - def set_score(self, score): self.score = score - def add_score(self, value): self.score.append(value) - def insert_score(self, index, value): self.score[index] = value - def get_notes(self): return self.notes - def set_notes(self, notes): self.notes = notes - def get_id(self): return self.id - def set_id(self, id): self.id = id - def export(self, outfile, level, namespace_='ortho:', name_='geneRef', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='geneRef') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='geneRef'): - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id="%s"' % self.gds_format_integer(self.id, input_name='id')) - def exportChildren(self, outfile, level, namespace_='ortho:', name_='geneRef', fromsubclass_=False): - for score_ in self.score: - score_.export(outfile, level, namespace_, name_='score') - if self.notes: - self.notes.export(outfile, level, namespace_, name_='notes') - def hasContent_(self): - if ( - self.score or - self.notes is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='geneRef'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = %d,\n' % (self.id,)) - def exportLiteralChildren(self, outfile, level, name_): - showIndent(outfile, level) - outfile.write('score=[\n') - level += 1 - for score_ in self.score: - showIndent(outfile, level) - outfile.write('model_.score(\n') - score_.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.notes is not None: - showIndent(outfile, level) - outfile.write('notes=model_.notes(\n') - self.notes.exportLiteral(outfile, level) - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - try: - self.id = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'score': - obj_ = score.factory() - obj_.build(child_) - self.score.append(obj_) - elif nodeName_ == 'notes': - obj_ = notes.factory() - obj_.build(child_) - self.set_notes(obj_) -# end class geneRef - - -class scoreDef(GeneratedsSuper): - """The scoreDef element defines a score. One of the concepts of - orthoXML is to be as flexible as possible but still uniformly - parsable. Part of this is to allow every ortholog resource to - give their own types of scores for groups or group members, - which is done using score elements. Score elements can be - defined to apply to either groups or geneRefs. It is possible to - define multiple scores. An internal identifier to link to the - scoreDef from a score element. Description of the score.""" - subclass = None - superclass = None - def __init__(self, id=None, desc=None, valueOf_=None): - self.id = _cast(None, id) - self.desc = _cast(None, desc) - pass - def factory(*args_, **kwargs_): - if scoreDef.subclass: - return scoreDef.subclass(*args_, **kwargs_) - else: - return scoreDef(*args_, **kwargs_) - factory = staticmethod(factory) - def get_id(self): return self.id - def set_id(self, id): self.id = id - def get_desc(self): return self.desc - def set_desc(self, desc): self.desc = desc - def export(self, outfile, level, namespace_='ortho:', name_='scoreDef', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='scoreDef') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='scoreDef'): - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id=%s' % (quote_attrib(self.id), )) - if self.desc is not None and 'desc' not in already_processed: - already_processed.append('desc') - outfile.write(' desc=%s' % (self.gds_format_string(quote_attrib(self.desc).encode(ExternalEncoding), input_name='desc'), )) - def exportChildren(self, outfile, level, namespace_='ortho:', name_='scoreDef', fromsubclass_=False): - pass - def hasContent_(self): - if ( - - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='scoreDef'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = "%s",\n' % (self.id,)) - if self.desc is not None and 'desc' not in already_processed: - already_processed.append('desc') - showIndent(outfile, level) - outfile.write('desc = "%s",\n' % (self.desc,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - self.id = value - value = find_attr_value_('desc', node) - if value is not None and 'desc' not in already_processed: - already_processed.append('desc') - self.desc = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class scoreDef - - -class score(GeneratedsSuper): - """The score element gives the value of a score and links it to the - scoreDef element, which defines the score. It can be child of a - group or a geneRef element to allow scoring on different levels. - An identifier linking to the scoreDef element, which defines the - score. The actual value of the score. For instance a confidence - score of a group member.""" - subclass = None - superclass = None - def __init__(self, id=None, value=None, valueOf_=None): - self.id = _cast(None, id) - self.value = _cast(float, value) - pass - def factory(*args_, **kwargs_): - if score.subclass: - return score.subclass(*args_, **kwargs_) - else: - return score(*args_, **kwargs_) - factory = staticmethod(factory) - def get_id(self): return self.id - def set_id(self, id): self.id = id - def get_value(self): return self.value - def set_value(self, value): self.value = value - def export(self, outfile, level, namespace_='ortho:', name_='score', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='score') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='score'): - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id=%s' % (quote_attrib(self.id), )) - if self.value is not None and 'value' not in already_processed: - already_processed.append('value') - outfile.write(' value="%s"' % self.gds_format_float(self.value, input_name='value')) - def exportChildren(self, outfile, level, namespace_='ortho:', name_='score', fromsubclass_=False): - pass - def hasContent_(self): - if ( - - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='score'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = "%s",\n' % (self.id,)) - if self.value is not None and 'value' not in already_processed: - already_processed.append('value') - showIndent(outfile, level) - outfile.write('value = %f,\n' % (self.value,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - self.id = value - value = find_attr_value_('value', node) - if value is not None and 'value' not in already_processed: - already_processed.append('value') - try: - self.value = float(value) - except ValueError, exp: - raise ValueError('Bad float/double attribute (value): %s' % exp) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class score - - -class property(GeneratedsSuper): - """Key-value pair for group annotations, for instance statistics about - the group members. The key of the key-value annotation pair. The - value of the key-value annotation pair. Optional to allow flag - like annotations.""" - subclass = None - superclass = None - def __init__(self, name=None, value=None, valueOf_=None): - self.name = _cast(None, name) - self.value = _cast(None, value) - pass - def factory(*args_, **kwargs_): - if property.subclass: - return property.subclass(*args_, **kwargs_) - else: - return property(*args_, **kwargs_) - factory = staticmethod(factory) - def get_name(self): return self.name - def set_name(self, name): self.name = name - def get_value(self): return self.value - def set_value(self, value): self.value = value - def export(self, outfile, level, namespace_='ortho:', name_='property', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='property') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='property'): - if self.name is not None and 'name' not in already_processed: - already_processed.append('name') - outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) - if self.value is not None and 'value' not in already_processed: - already_processed.append('value') - outfile.write(' value=%s' % (self.gds_format_string(quote_attrib(self.value).encode(ExternalEncoding), input_name='value'), )) - def exportChildren(self, outfile, level, namespace_='ortho:', name_='property', fromsubclass_=False): - pass - def hasContent_(self): - if ( - - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='property'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.name is not None and 'name' not in already_processed: - already_processed.append('name') - showIndent(outfile, level) - outfile.write('name = "%s",\n' % (self.name,)) - if self.value is not None and 'value' not in already_processed: - already_processed.append('value') - showIndent(outfile, level) - outfile.write('value = "%s",\n' % (self.value,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('name', node) - if value is not None and 'name' not in already_processed: - already_processed.append('name') - self.name = value - value = find_attr_value_('value', node) - if value is not None and 'value' not in already_processed: - already_processed.append('value') - self.value = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class property - - -class notes(GeneratedsSuper): - """The notes element is a special element, which allows adding - information that is not general enough to be part of the - standard. I.e. something specific to a particular ortholog - database or algorithm. Notes elements will not be validated, so - any child elements are legal. Notes elements can be children of - the root element orthoXML, the species element, the - orthologGroup element, the paralogGroup element, or the geneRef - element.""" - subclass = None - superclass = None - def __init__(self, valueOf_=None, mixedclass_=None, content_=None): - self.valueOf_ = valueOf_ - if mixedclass_ is None: - self.mixedclass_ = MixedContainer - else: - self.mixedclass_ = mixedclass_ - if content_ is None: - self.content_ = [] - else: - self.content_ = content_ - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if notes.subclass: - return notes.subclass(*args_, **kwargs_) - else: - return notes(*args_, **kwargs_) - factory = staticmethod(factory) - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def export(self, outfile, level, namespace_='ortho:', name_='notes', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='notes') - outfile.write('>') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - def exportAttributes(self, outfile, level, already_processed, namespace_='ortho:', name_='notes'): - pass - def exportChildren(self, outfile, level, namespace_='ortho:', name_='notes', fromsubclass_=False): - pass - def hasContent_(self): - if ( - self.valueOf_ - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='notes'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - pass - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - self.valueOf_ = get_all_text_(node) - if node.text is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', node.text) - self.content_.append(obj_) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if not fromsubclass_ and child_.tail is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.tail) - self.content_.append(obj_) - pass -# end class notes - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - -def usage(): - print USAGE_TEXT - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - rootClass = globals().get(tag) - return tag, rootClass - - -def parse(inFileName): - doc = parsexml_(inFileName) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'orthoXML' - rootClass = orthoXML - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## sys.stdout.write('\n') -## rootObj.export(sys.stdout, 0, name_=rootTag, -## namespacedef_='xmlns:ortho="http://orthoXML.org/2011/"') - return rootObj - - -def parseString(inString): - from StringIO import StringIO - doc = parsexml_(StringIO(inString)) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'orthoXML' - rootClass = orthoXML - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## sys.stdout.write('\n') -## rootObj.export(sys.stdout, 0, name_="orthoXML", -## namespacedef_='xmlns:ortho="http://orthoXML.org/2011/"') - return rootObj - - -def parseLiteral(inFileName): - doc = parsexml_(inFileName) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'orthoXML' - rootClass = orthoXML - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## sys.stdout.write('#from orthoxml import *\n\n') -## sys.stdout.write('import orthoxml as model_\n\n') -## sys.stdout.write('rootObj = model_.rootTag(\n') -## rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) -## sys.stdout.write(')\n') - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - - -__all__ = [ - "database", - "gene", - "geneRef", - "genes", - "group", - "groups", - "notes", - "orthoXML", - "property", - "score", - "scoreDef", - "scores", - "species" - ] diff --git a/ete2/parser/__init__.py b/ete2/parser/__init__.py deleted file mode 100644 index 0dc0832..0000000 --- a/ete2/parser/__init__.py +++ /dev/null @@ -1,41 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - diff --git a/ete2/parser/__init__.pyc b/ete2/parser/__init__.pyc deleted file mode 100644 index 50e1100..0000000 Binary files a/ete2/parser/__init__.pyc and /dev/null differ diff --git a/ete2/parser/fasta.py b/ete2/parser/fasta.py deleted file mode 100644 index e70fb52..0000000 --- a/ete2/parser/fasta.py +++ /dev/null @@ -1,129 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -import os -import string -import textwrap -from sys import stderr as STDERR - -def read_fasta(source, obj=None, header_delimiter="\t", fix_duplicates=True): - """ Reads a collection of sequences econded in FASTA format.""" - - if obj is None: - from ete2.coretype import seqgroup - SC = seqgroup.SeqGroup() - else: - SC = obj - - names = set([]) - seq_id = -1 - - # Prepares handle from which read sequences - if os.path.isfile(source): - _source = open(source, "rU") - else: - _source = iter(source.split("\n")) - - seq_name = None - for line in _source: - line = line.strip() - if line.startswith('#') or not line: - continue - # Reads seq number - elif line.startswith('>'): - # Checks if previous name had seq - if seq_id>-1 and SC.id2seq[seq_id] == "": - raise Exception, "No sequence found for "+seq_name - - seq_id += 1 - # Takes header info - seq_header_fields = map(string.strip, line[1:].split(header_delimiter)) - seq_name = seq_header_fields[0] - - # Checks for duplicated seq names - if fix_duplicates and seq_name in names: - tag = str(len([k for k in SC.name2id.keys() if k.endswith(seq_name)])) - old_name = seq_name - seq_name = tag+"_"+seq_name - print >>STDERR, "Duplicated entry [%s] was renamed to [%s]" %(old_name, seq_name) - - # stores seq_name - SC.id2seq[seq_id] = "" - SC.id2name[seq_id] = seq_name - SC.name2id[seq_name] = seq_id - SC.id2comment[seq_id] = seq_header_fields[1:] - names.add(seq_name) - - else: - if seq_name is None: - raise Exception, "Error reading sequences: Wrong format." - - # removes all white spaces in line - s = line.strip().replace(" ","") - - # append to seq_string - SC.id2seq[seq_id] += s - - if seq_name and SC.id2seq[seq_id] == "": - print >>STDERR, seq_name,"has no sequence" - return None - - # Everything ok - return SC - -def write_fasta(sequences, outfile = None, seqwidth = 80): - """ Writes a SeqGroup python object using FASTA format. """ - - wrapper = textwrap.TextWrapper() - wrapper.break_on_hyphens = False - wrapper.replace_whitespace = False - wrapper.expand_tabs = False - wrapper.break_long_words = True - wrapper.width = 80 - text = '\n'.join([">%s\n%s\n" %( "\t".join([name]+comment), wrapper.fill(seq)) for - name, seq, comment in sequences]) - - if outfile is not None: - OUT = open(outfile,"w") - OUT.write(text) - OUT.close() - else: - return text diff --git a/ete2/parser/fasta.pyc b/ete2/parser/fasta.pyc deleted file mode 100644 index 950ce29..0000000 Binary files a/ete2/parser/fasta.pyc and /dev/null differ diff --git a/ete2/parser/newick.py b/ete2/parser/newick.py deleted file mode 100644 index aba4a0a..0000000 --- a/ete2/parser/newick.py +++ /dev/null @@ -1,436 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -import re -import os -import base64 - -__all__ = ["read_newick", "write_newick", "print_supported_formats"] - -# Regular expressions used for reading newick format -_ILEGAL_NEWICK_CHARS = ":;(),\[\]\t\n\r=" -_NON_PRINTABLE_CHARS_RE = "[\x00-\x1f]+" - -_NHX_RE = "\[&&NHX:[^\]]*\]" -_FLOAT_RE = "[+-]?\d+\.?\d*(?:[eE][-+]\d+)?" -#_FLOAT_RE = "[+-]?\d+\.?\d*" -_NAME_RE = "[^():,;\[\]]+" - -DEFAULT_DIST = 1.0 -DEFAULT_NAME = '' -DEFAULT_SUPPORT = 1.0 - - -# Allowed formats. This table is used to read and write newick using -# different convenctions. You can also add your own formats in an easy way. -# -# -# FORMAT: [[LeafAttr1, LeafAttr1Type, Strict?], [LeafAttr2, LeafAttr2Type, Strict?],\ -# [InternalAttr1, InternalAttr1Type, Strict?], [InternalAttr2, InternalAttr2Type, Strict?]] -# -# Attributes are placed in the newick as follows: -# -# .... ,LeafAttr1:LeafAttr2)InternalAttr1:InternalAttr2 ... -# -# -# /-A -# -NoName--| -# | /-B -# \C-------| -# | /-D -# \E-------| -# \-G -# -# Format 0 = (A:0.350596,(B:0.728431,(D:0.609498,G:0.125729)1.000000:0.642905)1.000000:0.567737); -# Format 1 = (A:0.350596,(B:0.728431,(D:0.609498,G:0.125729)E:0.642905)C:0.567737); -# Format 2 = (A:0.350596,(B:0.728431,(D:0.609498,G:0.125729)1.000000:0.642905)1.000000:0.567737); -# Format 3 = (A:0.350596,(B:0.728431,(D:0.609498,G:0.125729)E:0.642905)C:0.567737); -# Format 4 = (A:0.350596,(B:0.728431,(D:0.609498,G:0.125729))); -# Format 5 = (A:0.350596,(B:0.728431,(D:0.609498,G:0.125729):0.642905):0.567737); -# Format 6 = (A:0.350596,(B:0.728431,(D:0.609498,G:0.125729)E)C); -# Format 7 = (A,(B,(D,G)E)C); -# Format 8 = (A,(B,(D,G))); -# Format 9 = (,(,(,))); - -NW_FORMAT = { - 0: [['name', str, True], ["dist", float, True], ['support', float, True], ["dist", float, True]], # Flexible with support - 1: [['name', str, True], ["dist", float, True], ['name', str, True], ["dist", float, True]], # Flexible with internal node names - 2: [['name', str, False], ["dist", float, False], ['support', float, False], ["dist", float, False]],# Strict with support values - 3: [['name', str, False], ["dist", float, False], ['name', str, False], ["dist", float, False]], # Strict with internal node names - 4: [['name', str, False], ["dist", float, False], [None, None, False], [None, None, False]], - 5: [['name', str, False], ["dist", float, False], [None, None, False], ["dist", float, False]], - 6: [['name', str, False], [None, None, False], [None, None, False], ["dist", float, False]], - 7: [['name', str, False], ["dist", float, False], ["name", str, False], [None, None, False]], - 8: [['name', str, False], [None, None, False], ["name", str, False], [None, None, False]], - 9: [['name', str, False], [None, None, False], [None, None, False], [None, None, False]], # Only topology with node names - 100: [[None, None, False], [None, None, False], [None, None, False], [None, None, False]] # Only Topology -} - - -def format_node(node, node_type, format): - if node_type == "leaf": - container1 = NW_FORMAT[format][0][0] - container2 = NW_FORMAT[format][1][0] - converterFn1 = NW_FORMAT[format][0][1] - converterFn2 = NW_FORMAT[format][1][1] - else: - container1 = NW_FORMAT[format][2][0] - container2 = NW_FORMAT[format][3][0] - converterFn1 = NW_FORMAT[format][2][1] - converterFn2 = NW_FORMAT[format][3][1] - - if converterFn1 == str: - try: - FIRST_PART = re.sub("["+_ILEGAL_NEWICK_CHARS+"]", "_", \ - str(getattr(node, container1))) - except (AttributeError, TypeError): - FIRST_PART = "?" - - elif converterFn1 is None: - FIRST_PART = "" - else: - try: - #FIRST_PART = "%0.6f" %(converterFn2(getattr(node, container1))) - FIRST_PART = "%g" %(converterFn2(getattr(node, container1))) - except (ValueError, TypeError): - FIRST_PART = "?" - - - if converterFn2 == str: - try: - SECOND_PART = ":"+re.sub("["+_ILEGAL_NEWICK_CHARS+"]", "_", \ - str(getattr(node, container2))) - except (ValueError, TypeError): - SECOND_PART = ":?" - elif converterFn2 is None: - SECOND_PART = "" - else: - try: - #SECOND_PART = ":%0.6f" %(converterFn2(getattr(node, container2))) - SECOND_PART = ":%g" %(converterFn2(getattr(node, container2))) - except (ValueError, TypeError): - SECOND_PART = ":?" - - return "%s%s" %(FIRST_PART, SECOND_PART) - -# Used to write into specific formats -def node2leafformat(node, format): - safe_name = re.sub("["+_ILEGAL_NEWICK_CHARS+"]", "_", \ - str(getattr(node, "name"))) - - if format == 0 or format == 1 or format == 2 or format ==3: - return "%s:%0.6f" %(safe_name, node.dist) - elif format == 4 or format == 7: - return ":%0.6f" %(node.dist) - elif format == 5 or format == 6: - return "%s" %(safe_name) - -def node2internalformat(node, format): - safe_name = re.sub("["+_ILEGAL_NEWICK_CHARS+"]", "_", \ - str(getattr(node, "name"))) - if format == 0 or format == 1: - return "%0.6f:%0.6f" %(node.support, node.dist) - elif format == 2: - return "%s:%0.6f" %(safe_name, node.dist) - elif format == 3 or format == 4: - return ":%0.6f" %(node.dist) - elif format == 5: - return "%s" %(safe_name) - elif format == 6 or format == 7: - return "" - -def print_supported_formats(): - from ete2.coretype.tree import TreeNode - t = TreeNode() - t.populate(4, "ABCDEFGHI") - print t - for f in NW_FORMAT: - print "Format", f,"=", write_newick(t, features=None, format=f) - -class NewickError(Exception): - """Exception class designed for NewickIO errors.""" - pass - -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, basestring): - if os.path.exists(newick): - nw = open(newick, 'rU').read() - 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 _read_newick_from_string(nw, root_node, format): - """ Reads a newick string in the New Hampshire format. """ - - if nw.count('(') != nw.count(')'): - raise NewickError, 'Parentheses do not match. Broken tree structure' - - # white spaces and separators are removed - nw = re.sub("[\n\r\t]+", "", nw) - - current_parent = None - - # Ok, this is my own way of reading newick structures. I find it - # more flexible and elegant than other docummented methods. Don't - # know if I'm loosing much efficiency. It Starts by splitting the - # structure using open parentheses. Each of the resulting chunks - # represent an internal node. So for each chunk I create a new node - # that hungs from the current parent node. Each internal node chunk - # may contain information about terminal nodes hanging from the - # internal and clossing parenthessis (closing previously opened - # internal nodes). - # - # Enjoy. - # by JHC ;) - - # Skip the first chunk. It is always == '' - for internal_node in nw.split("(")[1:]: - # If this is the root of tree, use the root_node instead of - # creating it, otherwise make a new one. - if current_parent is None: - current_parent = root_node - else: - current_parent = current_parent.add_child() - # We can only find leaf nodes within this chunk, since rest of - # internal nodes will be in the next newick chunks - possible_leaves = internal_node.split(",") - for i, leaf in enumerate(possible_leaves): - # Any resulting sub-chunk resulting from splitting by commas can - # be considered (tpologically) as a child to the current parent - # node. We only discard chunks if they are empty and in the last - # possition, meaining that the next brother is not terminal bu - # internal node (will be visited in the next newick chunk) - if leaf.strip() == '' and i == len(possible_leaves)-1: - continue - # Leaf text strings may end with a variable number of clossing - # parenthesis. For each ')' we read the information of the - # current node, close it and go up one more node. - clossing_nodes = leaf.split(")") - # first par contain leaf info - _read_node_data(clossing_nodes[0], current_parent, "leaf", format) - # The next parts containg clossing nodes and info about the - # internal nodes. - if len(clossing_nodes)>1: - for closing_internal in clossing_nodes[1:]: - if closing_internal.strip() ==";": continue - _read_node_data(closing_internal, current_parent, "internal", format) - current_parent = current_parent.up - return root_node - -def _parse_extra_features(node, NHX_string): - """ Reads node's extra data form its NHX string. NHX uses this - format: [&&NHX:prop1=value1:prop2=value2] """ - NHX_string = NHX_string.replace("[&&NHX:", "") - NHX_string = NHX_string.replace("]", "") - for field in NHX_string.split(":"): - try: - pname, pvalue = field.split("=") - except ValueError, e: - print NHX_string, field.split("=") - raise ValueError, e - node.add_feature(pname, pvalue) - -def _read_node_data(subnw, current_node, node_type, format): - """ Reads a leaf node from a subpart of the original newick - tree """ - - if node_type == "leaf" or node_type == "single": - if node_type == "leaf": - node = current_node.add_child() - else: - node = current_node - container1 = NW_FORMAT[format][0][0] - container2 = NW_FORMAT[format][1][0] - converterFn1 = NW_FORMAT[format][0][1] - converterFn2 = NW_FORMAT[format][1][1] - flexible1 = NW_FORMAT[format][0][2] - flexible2 = NW_FORMAT[format][1][2] - else: - node = current_node - container1 = NW_FORMAT[format][2][0] - container2 = NW_FORMAT[format][3][0] - converterFn1 = NW_FORMAT[format][2][1] - converterFn2 = NW_FORMAT[format][3][1] - flexible1 = NW_FORMAT[format][2][2] - flexible2 = NW_FORMAT[format][3][2] - - if converterFn1 == str: - FIRST_MATCH = "("+_NAME_RE+")" - elif converterFn1 == float: - FIRST_MATCH = "("+_FLOAT_RE+")" - elif converterFn1 is None: - FIRST_MATCH = '()' - - if converterFn2 == str: - SECOND_MATCH = "(:"+_NAME_RE+")" - elif converterFn2 == float: - SECOND_MATCH = "(:"+_FLOAT_RE+")" - elif converterFn2 is None: - SECOND_MATCH = '()' - - if flexible1: - FIRST_MATCH += "?" - if flexible2: - SECOND_MATCH += "?" - - MATCH = '%s\s*%s\s*(%s)?' % (FIRST_MATCH, SECOND_MATCH, _NHX_RE) - data = re.match(MATCH, subnw) - if data: - data = data.groups() - if data[0] is not None and data[0] != '': - node.add_feature(container1, converterFn1(data[0].strip())) - - if data[1] is not None and data[1] != '': - node.add_feature(container2, converterFn2(data[1][1:].strip())) - - if data[2] is not None \ - and data[2].startswith("[&&NHX"): - _parse_extra_features(node, data[2]) - else: - raise NewickError, "Unexpected leaf node format:\n\t"+ subnw[0:50] + "[%s]" %format - return - -# def write_newick_recursive(node, features=None, format=1, _is_root=True): -# """ Recursively reads a tree structure and returns its NHX -# representation. """ -# newick = "" -# if not node.children: -# safe_name = re.sub("["+_ILEGAL_NEWICK_CHARS+"]", "_", \ -# str(getattr(node, "name"))) - -# newick += format_node(node, "leaf", format) -# newick += _get_features_string(node, features) -# #return newick - -# else: -# if node.children: -# newick+= "(" -# for cnode in node.children: -# newick += write_newick(cnode, features, format=format,\ -# _is_root = False) -# # After last child is processed, add closing string -# if cnode == node.children[-1]: -# newick += ")" -# if node.up is not None: -# newick += format_node(node, "internal", format) -# newick += _get_features_string(node, features) -# else: -# newick += ',' - -# if _is_root: -# newick += ";" -# return newick - -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) - -def _get_features_string(self, features=None): - """ Generates the extended newick string NHX with extra data about - a node. """ - string = "" - if features is None: - features = [] - elif features == []: - features = self.features - - for pr in features: - if hasattr(self, pr): - value = re.sub("["+_ILEGAL_NEWICK_CHARS+"]", "_", \ - str(getattr(self, pr))) - if string != "": - string +=":" - string +="%s=%s" %(pr, str(value)) - if string != "": - string = "[&&NHX:"+string+"]" - - return string diff --git a/ete2/parser/newick.pyc b/ete2/parser/newick.pyc deleted file mode 100644 index 88d30ef..0000000 Binary files a/ete2/parser/newick.pyc and /dev/null differ diff --git a/ete2/parser/paml.py b/ete2/parser/paml.py deleted file mode 100644 index e72427b..0000000 --- a/ete2/parser/paml.py +++ /dev/null @@ -1,178 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - - -import os -import string -from sys import stderr as STDERR -from re import search - -def read_paml (source, obj=None, header_delimiter="\t", fix_duplicates=True): - """ Reads a collection of sequences econded in PAML format... that is, something between PHYLIP and fasta - - 3 6 - seq1 - ATGATG - seq2 - ATGATG - seq3 - ATGATG - - or - - 3 6 - >seq1 - ATGATG - >seq2 - ATGATG - >seq3 - ATGATG - - or - - >seq1 - ATGATG - >seq2 - ATGATG - >seq3 - ATGATG - - """ - - if obj is None: - from ete2.coretype import seqgroup - SC = seqgroup.SeqGroup() - else: - SC = obj - - names = set([]) - seq_id = -1 - - # Prepares handle from which read sequences - if os.path.isfile(source): - _source = open(source, "rU") - else: - _source = iter(source.split("\n")) - - seq_name = None - num_seq = 0 - len_seq = 0 - in_seq = False - for line in _source: - line = line.strip() - if line.startswith('#') or not line: - continue - # Reads seq number - elif line.startswith('>') or ((num_seq and len_seq) and not in_seq): - line = line.replace('>','') - # Checks if previous name had seq - if seq_id>-1 and SC.id2seq[seq_id] == "": - raise Exception, "No sequence found for "+seq_name - - seq_id += 1 - # Takes header info - seq_header_fields = map(string.strip, line.split(header_delimiter)) - seq_name = seq_header_fields[0] - - # Checks for duplicated seq names - if fix_duplicates and seq_name in names: - tag = str(len([k for k in SC.name2id.keys() if k.endswith(seq_name)])) - old_name = seq_name - seq_name = tag+"_"+seq_name - print >>STDERR, "Duplicated entry [%s] was renamed to [%s]" %(old_name, seq_name) - - # stores seq_name - SC.id2seq[seq_id] = "" - SC.id2name[seq_id] = seq_name - SC.name2id[seq_name] = seq_id - SC.id2comment[seq_id] = seq_header_fields[1:] - names.add(seq_name) - in_seq = True - else: - if seq_name is None: - if search ('^[0-9]+ *[0-9]+$', line): - num_seq, len_seq = line.strip().split() - num_seq = int(num_seq) - len_seq = int(len_seq) - continue - if line.startswith('\n'): - continue - raise Exception, "Error reading sequences: Wrong format.\n"+line - elif in_seq: - # removes all white spaces in line - s = line.strip().replace(" ","") - - # append to seq_string - SC.id2seq[seq_id] += s - if len_seq: - if len(SC.id2seq[seq_id]) == len_seq: - in_seq=False - elif len(SC.id2seq[seq_id]) > len_seq: - raise Exception, "Error reading sequences: Wrong sequence length.\n"+line - - if seq_name and SC.id2seq[seq_id] == "": - print >>STDERR, seq_name,"has no sequence" - return None - - # Everything ok - return SC - -def write_paml(sequences, outfile = None, seqwidth = 80): - """ - Writes a SeqGroup python object using PAML format. - sequences are ordered, because PAML labels tree according to this. - """ - text = ' %d %d\n' % (len (sequences), len (sequences.get_entries()[0][1])) - text += '\n'.join(["%s\n%s" %( "\t".join([name]+comment), _seq2str(seq)) for - name, seq, comment in sorted(sequences)]) - if outfile is not None: - OUT = open(outfile,"w") - OUT.write(text) - OUT.close() - else: - return text - -def _seq2str(seq, seqwidth = 80): - sequence = "" - for i in xrange(0,len(seq),seqwidth): - sequence+= seq[i:i+seqwidth] + "\n" - return sequence - diff --git a/ete2/parser/paml.pyc b/ete2/parser/paml.pyc deleted file mode 100644 index 7b33343..0000000 Binary files a/ete2/parser/paml.pyc and /dev/null differ diff --git a/ete2/parser/phylip.py b/ete2/parser/phylip.py deleted file mode 100644 index cadc75e..0000000 --- a/ete2/parser/phylip.py +++ /dev/null @@ -1,214 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -import os -import re -from sys import stderr as STDERR - -def read_phylip(source, interleaved=True, obj=None, - relaxed=False, fix_duplicates=True): - if obj is None: - from ete2.coretype import SeqGroup - SG = SeqGroup() - else: - SG = obj - - # Prepares handle from which read sequences - if os.path.isfile(source): - _source = open(source, "rU") - else: - _source = iter(source.split("\n")) - - nchar, ntax = None, None - counter = 0 - id_counter = 0 - for line in _source: - line = line.strip("\n") - # Passes comments and blank lines - if not line or line[0] == "#": - continue - # Reads head - if not nchar or not ntax: - m = re.match("^\s*(\d+)\s+(\d+)",line) - if m: - ntax = int (m.groups()[0]) - nchar = int (m.groups()[1]) - else: - raise Exception, \ - "A first line with the alignment dimension is required" - # Reads sequences - else: - if not interleaved: - # Reads names and sequences - if SG.id2name.get(id_counter, None) is None: - if relaxed: - m = re.match("^([^ ]+)(.+)", line) - else: - m = re.match("^(.{10})(.+)", line) - if m: - name = m.groups()[0].strip() - if fix_duplicates and name in SG.name2id: - tag = str(len([k for k in SG.name2id.keys() \ - if k.endswith(name)])) - old_name = name - # Tag is in the beginning to avoid being - # cut it by the 10 chars limit - name = tag+"_"+name - print >>STDERR, \ - "Duplicated entry [%s] was renamed to [%s]" %\ - (old_name, name) - SG.id2name[id_counter] = name - SG.name2id[name] = id_counter - SG.id2seq[id_counter] = "" - line = m.groups()[1] - else: - raise Exception, \ - "Wrong phylip sequencial format." - SG.id2seq[id_counter] += re.sub("\s","", line) - if len(SG.id2seq[id_counter]) == nchar: - id_counter += 1 - name = None - elif len(SG.id2seq[id_counter]) > nchar: - raise Exception, \ - "Unexpected length of sequence [%s] [%s]." %(name,SG.id2seq[id_counter]) - else: - if len(SG)>STDERR, \ - "Duplicated entry [%s] was renamed to [%s]" %\ - (old_name, name) - SG.name2id[name] = id_counter - id_counter += 1 - else: - raise Exception, \ - "Unexpected number of sequences." - else: - seq = re.sub("\s", "", line) - if id_counter == len(SG): - id_counter = 0 - SG.id2seq[id_counter] += seq - id_counter += 1 - - if len(SG) != ntax: - raise Exception, \ - "Unexpected number of sequences." - - # Check lenght of all seqs - for i in SG.id2seq.keys(): - if len(SG.id2seq[i]) != nchar: - raise Exception, \ - "Unexpected lenght of sequence [%s]" %SG.id2name[i] - - return SG - -def write_phylip(aln, outfile=None, interleaved=True, relaxed=False): - width = 60 - seq_visited = set([]) - - show_name_warning = False - lenghts = set((len(seq) for seq in aln.id2seq.values())) - if len(lenghts) >1: - raise Exception, "Phylip format requires sequences of equal lenght." - seqlength = lenghts.pop() - - if not relaxed: - name_fix = 10 - else: - name_fix = max([len(name) for name in aln.id2name.values()]) - - alg_lines = [] - alg_text = " %d %d" %(len(aln), seqlength) - alg_lines.append(alg_text) - if interleaved: - visited = set([]) - for i in xrange(0, seqlength, width): - for j in aln.id2name.iterkeys(): #xrange(len(aln)): - name = aln.id2name[j] - if not relaxed and len(name)>name_fix: - name = name[:name_fix] - show_name_warning = True - - seq = aln.id2seq[j][i:i+width] - if j not in visited: - name_str = "%s " %name.ljust(name_fix) - visited.add(j) - else: - name_str = "".ljust(name_fix+3) - - seq_str = ' '.join([seq[k:k+10] for k in xrange(0, len(seq), 10)]) - line_str = "%s%s" %(name_str, seq_str) - alg_lines.append(line_str) - alg_lines.append("") - else: - for name, seq, comments in aln.iter_entries(): - if not relaxed and len(name)>10: - name = name[:name_fix] - show_name_warning = True - line_str = "%s %s\n%s" %\ - (name.ljust(name_fix), seq[0:width-name_fix-3], '\n'.join([seq[k:k+width] \ - for k in xrange(width-name_fix-3, len(seq), width)])) - alg_lines.append(line_str) - alg_lines.append("") - - - if show_name_warning: - print >>STDERR, "Warning! Some sequence names were cut to 10 characters!!" - alg_text = '\n'.join(alg_lines) - if outfile is not None: - OUT = open(outfile, "w") - OUT.write(alg_text) - OUT.close() - else: - return alg_text diff --git a/ete2/parser/phylip.pyc b/ete2/parser/phylip.pyc deleted file mode 100644 index af9d548..0000000 Binary files a/ete2/parser/phylip.pyc and /dev/null differ diff --git a/ete2/parser/text_arraytable.py b/ete2/parser/text_arraytable.py deleted file mode 100644 index 9fa3242..0000000 --- a/ete2/parser/text_arraytable.py +++ /dev/null @@ -1,157 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -#! /usr/bin/env python - -import re -from sys import stderr -import numpy - - -__all__ = ['read_arraytable', 'write_arraytable'] - -def read_arraytable(matrix_file, mtype="float", arraytable_object = None): - """ Reads a text tab-delimited matrix from file """ - - if arraytable_object is None: - from ete2.coretype import arraytable - A = arraytable.ArrayTable() - else: - A = arraytable_object - - A.mtype = mtype - temp_matrix = [] - rowname_counter = {} - colname_counter = {} - row_dup_flag = False - col_dup_flag = False - - # if matrix_file has many lines, tries to read it as the matrix - # itself. - if len(matrix_file.split("\n"))>1: - matrix_data = matrix_file.split("\n") - else: - matrix_data = open(matrix_file) - - for line in matrix_data: - # Clean up line - line = line.strip("\n") - #line = line.replace(" ","") - # Skip empty lines - if not line: - continue - # Get fields in line - fields = line.split("\t") - # Read column names - if line[0]=='#' and re.match("#NAMES",fields[0],re.IGNORECASE): - counter = 0 - for colname in fields[1:]: - colname = colname.strip() - - # Handle duplicated col names by adding a number - colname_counter[colname] = colname_counter.get(colname,0) + 1 - if colname in A.colValues: - colname += "_%d" % colname_counter[colname] - col_dup_flag = True - # Adds colname - A.colValues[colname] = None - A.colNames.append(colname) - if col_dup_flag: - print >>stderr, "Duplicated column names were renamed." - - # Skip comments - elif line[0]=='#': - continue - - # Read values (only when column names are loaded) - elif A.colNames: - # Checks shape - if len(fields)-1 != len(A.colNames): - raise ValueError, "Invalid number of columns. Expecting:%d" % len(A.colNames) - - # Extracts row name and remove it from fields - rowname = fields.pop(0).strip() - - # Handles duplicated row names by adding a number - rowname_counter[rowname] = rowname_counter.get(rowname,0) + 1 - if rowname in A.rowValues: - rowname += "_%d" % rowname_counter[rowname] - row_dup_names = True - - # Adds row name - A.rowValues[rowname] = None - A.rowNames.append(rowname) - - # Reads row values - values = [] - for f in fields: - if f.strip()=="": - f = numpy.nan - values.append(f) - temp_matrix.append(values) - else: - raise ValueError, "Column names are required." - - if row_dup_flag: - print >>stderr, "Duplicated row names were renamed." - - # Convert all read lines into a numpy matrix - vmatrix = numpy.array(temp_matrix).astype(A.mtype) - - # Updates indexes to link names and vectors in matrix - A._link_names2matrix(vmatrix) - return A - -def write_arraytable(A, fname, colnames=None): - if colnames is None: - colnames = [] - elif colnames == []: - colnames = A.colNames - - matrix = A.get_several_column_vectors(colnames) - matrix = matrix.swapaxes(0,1) - OUT = open(fname,"w") - print >>OUT, '\t'.join(["#NAMES"] + colnames) - counter = 0 - for rname in A.rowNames: - print >>OUT, '\t'.join(map(str,[rname]+matrix[counter].tolist())) - counter +=1 - OUT.close() diff --git a/ete2/parser/text_arraytable.pyc b/ete2/parser/text_arraytable.pyc deleted file mode 100644 index 12779bd..0000000 Binary files a/ete2/parser/text_arraytable.pyc and /dev/null differ diff --git a/ete2/phylo/__init__.py b/ete2/phylo/__init__.py deleted file mode 100644 index 34369a2..0000000 --- a/ete2/phylo/__init__.py +++ /dev/null @@ -1,45 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - - -from phylotree import * -from evolevents import * -__all__ = phylotree.__all__ + evolevents.__all__ diff --git a/ete2/phylo/__init__.pyc b/ete2/phylo/__init__.pyc deleted file mode 100644 index f8b8478..0000000 Binary files a/ete2/phylo/__init__.pyc and /dev/null differ diff --git a/ete2/phylo/evolevents.py b/ete2/phylo/evolevents.py deleted file mode 100644 index 83a932a..0000000 --- a/ete2/phylo/evolevents.py +++ /dev/null @@ -1,78 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -__all__ = ["EvolEvent"] - -class EvolEvent: - """ Basic evolutionary event. It stores all the information about an - event(node) ocurred in a phylogenetic tree. - - :attr:`etype` : ``D`` (Duplication), ``S`` (Speciation), ``L`` (gene loss), - - :attr:`in_seqs` : the list of sequences in one side of the event. - - :attr:`out_seqs` : the list of sequences in the other side of the event - - :attr:`node` : link to the event node in the tree - - """ - - def __init__(self): - self.etype = None # 'S=speciation D=duplication' - self.in_seqs = [] - self.out_seqs = [] - self.dup_score = None - self.sos = None - - # Not documented - self.inparalogs = None - self.outparalogs = None - self.outgroup_spcs = None # outgroup - self.e_newick = None # - self.root_age = None # estimated time for the outgroup node - self.orthologs = None - self.famSize = None - self.seed = None # Seed ID used to start the phylogenetic pipeline - self.branch_supports = [] - - - - diff --git a/ete2/phylo/evolevents.pyc b/ete2/phylo/evolevents.pyc deleted file mode 100644 index 86ad3d8..0000000 Binary files a/ete2/phylo/evolevents.pyc and /dev/null differ diff --git a/ete2/phylo/phylotree.py b/ete2/phylo/phylotree.py deleted file mode 100644 index 7be5d48..0000000 --- a/ete2/phylo/phylotree.py +++ /dev/null @@ -1,676 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - - -""" -This module defines the PhyloNode dataytype to manage phylogenetic -trees. It inheritates the coretype TreeNode and add some special -features to the the node instances. -""" - -import sys -import os -import re -import itertools -from collections import defaultdict -from ete2 import TreeNode, SeqGroup -from reconciliation import get_reconciled_tree -import spoverlap - -__all__ = ["PhyloNode", "PhyloTree"] - -def _parse_species(name): - return name[:3] - -def is_dup(n): - return getattr(n, "evoltype", None) == "D" - -def get_subtrees(tree, full_copy=False, features=None, newick_only=False): - """Calculate all possible species trees within a gene tree. I - tested several recursive and iterative approaches to do it and - this is the most efficient way I found. The method is now fast and - light enough to deal with very large gene trees, and it scales - linearly instead of exponentially. For instance, a tree with ~8000 - nodes, ~100 species and ~400 duplications returns ~10,000 sptrees - that could be loaded in few minutes. - - """ - - nid = 0 - dups = set() - n2nid = {} - nid2node = {} - n2subtrees = defaultdict(list) - for n in tree.traverse("postorder"): - n2nid[n] = nid - nid2node[nid] = n - nid += 1 - if n.children: - if is_dup(n): - dups.add(n2nid[n]) - subtrees = [] - for ch in n.children: - subtrees.extend(n2subtrees[n2nid[ch]]) - else: - subtrees = tuple([val for val in - itertools.product(n2subtrees[n2nid[n.children[0]]], - n2subtrees[n2nid[n.children[1]]])]) - else: - subtrees = tuple([n2nid[n]]) - - n2subtrees[n2nid[n]] = subtrees - for ch in n.children: - del n2subtrees[n2nid[ch]] - sp_trees = n2subtrees[n2nid[tree]] - return len(sp_trees), len(dups), iter_sptrees(sp_trees, nid2node, features, newick_only=newick_only) - -def iter_sptrees(sptrees, nid2node, features=None, newick_only=False): - """ Loads and map the species trees returned by get_subtrees""" - - features = set(features) if features else set() - features.update(["name"]) - - def _nodereplacer(match): - pre, b, post = match.groups() - node = nid2node[int(b)] - fstring = "" - if features: - fstring = "".join(["[&&NHX:", - ','.join(["%s=%s" %(f, getattr(node, f)) - for f in features if hasattr(node, f)]) - , "]"]) - - return ''.join([pre, node.name, fstring, post]) - - if newick_only: - id_match = re.compile("([^0-9])(\d+)([^0-9])") - for nw in sptrees: - yield re.sub(id_match, _nodereplacer, str(nw)+";") - else: - for nw in sptrees: - # I take advantage from the fact that I generated the subtrees - # using tuples, so str representation is actually a newick :) - t = PhyloTree(str(nw)+";") - # Map features from original tree - for leaf in t.iter_leaves(): - _nid = int(leaf.name) - for f in features: - leaf.add_feature(f, getattr(nid2node[_nid], f)) - yield t - -def _get_subtrees_recursive(node, full_copy=True): - if is_dup(node): - sp_trees = [] - for ch in node.children: - sp_trees.extend(_get_subtrees_recursive(ch, full_copy=full_copy)) - return sp_trees - - # saves a list of duplication nodes under current node - dups = [] - for _n in node.iter_leaves(is_leaf_fn=is_dup): - if is_dup(_n): - dups.append(_n) - - if dups: - # detach inner duplication nodes and stores their anchor point - subtrees = [] - for dp in dups: - # The real node to attach sibling subtress - anchor = dp.up - dp.detach() - - duptrees = [] - #get all sibling sptrees in each side of the - #duplication. Each subtree is pointed to its anchor - for ch in dp.children: - for subt in _get_subtrees_recursive(ch, full_copy=full_copy): - if not full_copy: - subt = node.__class__(subt) - subt.up = anchor - duptrees.append(subt) - - #all posible sptrees under this duplication are stored - subtrees.append(duptrees) - - # Generates all combinations of subtrees in sibling duplications - sp_trees = [] - for comb in itertools.product(*subtrees): - #each subtree is attached to its anchor point and make a copy - #of the final sp tree - for subt in comb: - #anchor = subt2anchor[subt] - if subt.up: - subt.up.children.append(subt) - #print subt.up - else: - sp_trees.append(subt) - if full_copy: - back_up = node.up - node.up = None - _node = node.copy() - node.up = back_up - else: - _node = node.write(format=9, features=["name", "evoltype"]) - sp_trees.append(_node) - # Clear current node - for subt in comb: - subt.up.children.pop(-1) - else: - if full_copy: - back_up = node.up - node.up = None - _node = node.copy() - node.up = back_up - else: - _node = node.write(format=9, features=["name", "evoltype"]) - #node.detach() - sp_trees = [_node] - - return sp_trees - -def get_subparts(n): - def is_dup(n): - return getattr(n, "evoltype", None) == "D" - - subtrees = [] - if is_dup(n): - for ch in n.get_children(): - ch.detach() - subtrees.extend(get_subparts(ch)) - else: - to_visit = [] - for _n in n.iter_leaves(is_leaf_fn=is_dup): - if is_dup(_n): - to_visit.append(_n) - - for _n in to_visit: - _n.detach() - - freaks = [_n for _n in n.iter_descendants() if - len(_n.children)==1 or (not hasattr(_n, "_leaf") and not _n.children)] - for s in freaks: - s.delete(prevent_nondicotomic=True) - - # Clean node structure to prevent nodes with only one child - while len(n.children) == 1: - n = n.children[0] - n.detach() - - if not n.children and not hasattr(n, "_leaf"): - pass - else: - subtrees.append(n) - - for _n in to_visit: - subtrees.extend(get_subparts(_n)) - - return subtrees - - -class PhyloNode(TreeNode): - """ - .. currentmodule:: ete2 - Extends the standard :class:`TreeNode` instance. It adds - specific attributes and methods to work with phylogentic trees. - - :argument newick: Path to the file containing the tree or, alternatively, - the text string containing the same information. - - :argument alignment: file containing a multiple sequence alignment. - - :argument alg_format: "fasta", "phylip" or "iphylip" (interleaved) - - :argument format: sub-newick format - - .. table:: - - ====== ============================================== - FORMAT DESCRIPTION - ====== ============================================== - 0 flexible with support values - 1 flexible with internal node names - 2 all branches + leaf names + internal supports - 3 all branches + all names - 4 leaf branches + leaf names - 5 internal and leaf branches + leaf names - 6 internal branches + leaf names - 7 leaf branches + all names - 8 all names - 9 leaf names - 100 topology only - ====== ============================================== - - :argument sp_naming_function: Pointer to a parsing python - function that receives nodename as first argument and returns - the species name (see - :func:`PhyloNode.set_species_naming_function`. By default, the - 3 first letter of nodes will be used as species identifiers. - - - - :returns: a tree node object which represents the base of the tree. - """ - - def _get_species(self): - if self._speciesFunction: - try: - return self._speciesFunction(self.name) - except: - return self._speciesFunction(self) - else: - return self._species - - def _set_species(self, value): - if self._speciesFunction: - pass - else: - self._species = value - - # This tweak overwrites the native 'name' attribute to create a - # property that updates the species code every time name is - # changed - - #: .. currentmodule:: ete2 - #: - #Species code associated to the node. This property can be - #automatically extracted from the TreeNode.name attribute or - #manually set (see :func:`PhyloNode.set_species_naming_function`). - species = property(fget = _get_species, fset = _set_species) - - def __init__(self, newick=None, alignment=None, alg_format="fasta", \ - sp_naming_function=_parse_species, format=0, **kargs): - - # _update names? - self._name = "NoName" - self._species = "Unknown" - self._speciesFunction = None - # Caution! native __init__ has to be called after setting - # _speciesFunction to None!! - TreeNode.__init__(self, newick=newick, format=format, **kargs) - - # This will be only executed after reading the whole tree, - # because the argument 'alignment' is not passed to the - # PhyloNode constructor during parsing - if alignment: - self.link_to_alignment(alignment, alg_format) - if newick: - self.set_species_naming_function(sp_naming_function) - - def __repr__(self): - return "PhyloTree node '%s' (%s)" %(self.name, hex(self.__hash__())) - - def set_species_naming_function(self, fn): - """ - Sets the parsing function used to extract species name from a - node's name. - - :argument fn: Pointer to a parsing python function that - receives nodename as first argument and returns the species - name. - - :: - - # Example of a parsing function to extract species names for - # all nodes in a given tree. - def parse_sp_name(node_name): - return node_name.split("_")[1] - tree.set_species_naming_function(parse_sp_name) - - """ - if fn: - for n in self.traverse(): - n._speciesFunction = fn - if n.is_leaf(): - n.features.add("species") - - def link_to_alignment(self, alignment, alg_format="fasta", **kwargs): - missing_leaves = [] - missing_internal = [] - if type(alignment) == SeqGroup: - alg = alignment - else: - alg = SeqGroup(alignment, format=alg_format, **kwargs) - # sets the seq of - for n in self.traverse(): - try: - n.add_feature("sequence",alg.get_seq(n.name)) - except KeyError: - if n.is_leaf(): - missing_leaves.append(n.name) - else: - missing_internal.append(n.name) - if len(missing_leaves)>0: - print >>sys.stderr, \ - "Warnning: [%d] terminal nodes could not be found in the alignment." %\ - len(missing_leaves) - # Show warning of not associated internal nodes. - # if len(missing_internal)>0: - # print >>sys.stderr, \ - # "Warnning: [%d] internal nodes could not be found in the alignment." %\ - # len(missing_leaves) - - def get_species(self): - """ Returns the set of species covered by its partition. """ - return set([l.species for l in self.iter_leaves()]) - - def iter_species(self): - """ Returns an iterator over the species grouped by this node. """ - spcs = set([]) - for l in self.iter_leaves(): - if l.species not in spcs: - spcs.add(l.species) - yield l.species - - def get_age(self, species2age): - return max([species2age[sp] for sp in self.get_species()]) - - def reconcile(self, species_tree): - """ Returns the reconcilied topology with the provided species - tree, and a list of evolutionary events inferred from such - reconciliation. """ - return get_reconciled_tree(self, species_tree, []) - - def get_my_evol_events(self, sos_thr=0.0): - """ Returns a list of duplication and speciation events in - which the current node has been involved. Scanned nodes are - also labeled internally as dup=True|False. You can access this - labels using the 'node.dup' sintaxis. - - Method: the algorithm scans all nodes from the given leafName to - the root. Nodes are assumed to be duplications when a species - overlap is found between its child linages. Method is described - more detail in: - - "The Human Phylome." Huerta-Cepas J, Dopazo H, Dopazo J, Gabaldon - T. Genome Biol. 2007;8(6):R109. - """ - return spoverlap.get_evol_events_from_leaf(self, sos_thr=sos_thr) - - def get_descendant_evol_events(self, sos_thr=0.0): - """ Returns a list of **all** duplication and speciation - events detected after this node. Nodes are assumed to be - duplications when a species overlap is found between its child - linages. Method is described more detail in: - - "The Human Phylome." Huerta-Cepas J, Dopazo H, Dopazo J, Gabaldon - T. Genome Biol. 2007;8(6):R109. - """ - return spoverlap.get_evol_events_from_root(self, sos_thr=sos_thr) - - def get_farthest_oldest_leaf(self, species2age, is_leaf_fn=None): - """ Returns the farthest oldest leaf to the current - one. It requires an species2age dictionary with the age - estimation for all species. - - :argument None is_leaf_fn: A pointer to a function that - receives a node instance as unique argument and returns True - or False. It can be used to dynamically collapse nodes, so - they are seen as leaves. - - """ - - root = self.get_tree_root() - outgroup_dist = 0 - outgroup_node = self - outgroup_age = 0 # self.get_age(species2age) - - for leaf in root.iter_leaves(is_leaf_fn=is_leaf_fn): - if leaf.get_age(species2age) > outgroup_age: - outgroup_dist = leaf.get_distance(self) - outgroup_node = leaf - outgroup_age = species2age[leaf.get_species().pop()] - elif leaf.get_age(species2age) == outgroup_age: - dist = leaf.get_distance(self) - if dist>outgroup_dist: - outgroup_dist = leaf.get_distance(self) - outgroup_node = leaf - outgroup_age = species2age[leaf.get_species().pop()] - return outgroup_node - - def get_farthest_oldest_node(self, species2age): - """ - .. versionadded:: 2.1 - - Returns the farthest oldest node (leaf or internal). The - difference with get_farthest_oldest_leaf() is that in this - function internal nodes grouping seqs from the same species - are collapsed. - """ - - # I use a custom is_leaf() function to collapse nodes groups - # seqs from the same species - is_leaf = lambda node: len(node.get_species())==1 - return self.get_farthest_oldest_leaf(species2age, is_leaf_fn=is_leaf) - - def get_age_balanced_outgroup(self, species2age): - """ - .. versionadded:: 2.2 - - Returns the node better balance current tree structure - according to the topological age of the different leaves and - internal node sizes. - - :param species2age: A dictionary translating from leaf names - into a topological age. - - .. warning: This is currently an experimental method!! - - """ - root = self - all_seqs = set(self.get_leaf_names()) - outgroup_dist = 0 - best_balance = max(species2age.values()) - outgroup_node = self - outgroup_size = 0 - - for leaf in root.iter_descendants(): - leaf_seqs = set(leaf.get_leaf_names()) - size = len(leaf_seqs) - - leaf_species =[self._speciesFunction(s) for s in leaf_seqs] - out_species = [self._speciesFunction(s) for s in all_seqs-leaf_seqs] - - leaf_age_min = min([species2age[sp] for sp in leaf_species]) - out_age_min = min([species2age[sp] for sp in out_species]) - leaf_age_max = max([species2age[sp] for sp in leaf_species]) - out_age_max = max([species2age[sp] for sp in out_species]) - leaf_age = leaf_age_max - leaf_age_min - out_age = out_age_max - out_age_min - - age_inbalance = abs(out_age - leaf_age) - - # DEBUG ONLY - # leaf.add_features(age_inbalance = age_inbalance, age=leaf_age) - - update = False - if age_inbalance < best_balance: - update = True - elif age_inbalance == best_balance: - if size > outgroup_size: - update = True - elif size == outgroup_size: - dist = self.get_distance(leaf) - outgroup_dist = self.get_distance(outgroup_node) - if dist > outgroup_dist: - update = True - - if update: - best_balance = age_inbalance - outgroup_node = leaf - outgroup_size = size - - return outgroup_node - - def get_speciation_trees(self, map_features=None, autodetect_duplications=True, - newick_only=False): - """ - .. versionadded: 2.2 - - Calculates all possible species trees contained within a - duplicated gene family tree as described in `Treeko - `_ (see `Marcet and Gabaldon, - 2011 `_ ). - - - :argument True autodetect_duplications: If True, duplication - nodes will be automatically detected using the Species Overlap - algorithm (:func:`PhyloNode.get_descendants_evol_events`. If - False, duplication nodes within the original tree are expected - to contain the feature "evoltype=D". - - :argument None features: A list of features that should be - mapped from the original gene family tree to each species - tree subtree. - - :returns: (number_of_sptrees, number_of_dups, species_tree_iterator) - - """ - t = self - if autodetect_duplications: - #n2content, n2species = t.get_node2species() - n2content = t.get_cached_content() - n2species = t.get_cached_content(store_attr="species") - for node in n2content: - sp_subtotal = sum([len(n2species[_ch]) for _ch in node.children]) - if len(n2species[node]) > 1 and len(n2species[node]) != sp_subtotal: - node.add_features(evoltype="D") - - sp_trees = get_subtrees(t, features=map_features, newick_only=newick_only) - - return sp_trees - - def __get_speciation_trees_recursive(self): - """ experimental and testing """ - t = self.copy() - if autodetect_duplications: - dups = 0 - #n2content, n2species = t.get_node2species() - n2content = t.get_cached_content() - n2species = t.get_cached_content(store_attr="species") - - #print "Detecting dups" - for node in n2content: - sp_subtotal = sum([len(n2species[_ch]) for _ch in node.children]) - if len(n2species[node]) > 1 and len(n2species[node]) != sp_subtotal: - node.add_features(evoltype="D") - dups += 1 - elif node.is_leaf(): - node._leaf = True - #print dups - else: - for node in t.iter_leaves(): - node._leaf = True - subtrees = _get_subtrees_recursive(t) - return len(subtrees), 0, subtrees - - def split_by_dups(self, autodetect_duplications=True): - """ - .. versionadded: 2.2 - - Returns the list of all subtrees resulting from splitting - current tree by its duplication nodes. - - :argument True autodetect_duplications: If True, duplication - nodes will be automatically detected using the Species Overlap - algorithm (:func:`PhyloNode.get_descendants_evol_events`. If - False, duplication nodes within the original tree are expected - to contain the feature "evoltype=D". - - :returns: species_trees - """ - try: - t = self.copy() - except Exception: - t = self.copy("deepcopy") - - if autodetect_duplications: - dups = 0 - #n2content, n2species = t.get_node2species() - n2content = t.get_cached_content() - n2species = t.get_cached_content(store_attr="species") - - #print "Detecting dups" - for node in n2content: - sp_subtotal = sum([len(n2species[_ch]) for _ch in node.children]) - if len(n2species[node]) > 1 and len(n2species[node]) != sp_subtotal: - node.add_features(evoltype="D") - dups += 1 - elif node.is_leaf(): - node._leaf = True - #print dups - else: - for node in t.iter_leaves(): - node._leaf = True - sp_trees = get_subparts(t) - return sp_trees - - def collapse_lineage_specific_expansions(self, species=None, return_copy=True): - """ Converts lineage specific expansion nodes into a single - tip node (randomly chosen from tips within the expansion). - - :param None species: If supplied, only expansions matching the - species criteria will be pruned. When None, all expansions - within the tree will be processed. - - """ - if species and type(species) not in set(["set", "frozenset"]): - raise ValueError("species argument should be a set, frozenset") - - prunned = self.copy("deepcopy") if return_copy else self - n2sp = prunned.get_cached_content(store_attr="species") - n2leaves = prunned.get_cached_content() - is_expansion = lambda n: (len(n2sp[n])==1 and len(n2leaves[n])>1 - and (species is None or species & n2sp[n])) - for n in prunned.get_leaves(is_leaf_fn=is_expansion): - repre = list(n2leaves[n])[0] - repre.detach() - if n is not prunned: - n.up.add_child(repre) - n.detach() - else: - return repre - - return prunned - - -#: .. currentmodule:: ete2 -# -PhyloTree = PhyloNode diff --git a/ete2/phylo/phylotree.pyc b/ete2/phylo/phylotree.pyc deleted file mode 100644 index 85949d4..0000000 Binary files a/ete2/phylo/phylotree.pyc and /dev/null differ diff --git a/ete2/phylo/reconciliation.py b/ete2/phylo/reconciliation.py deleted file mode 100644 index a9ac45b..0000000 --- a/ete2/phylo/reconciliation.py +++ /dev/null @@ -1,152 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -import copy -from evolevents import EvolEvent - - -def get_reconciled_tree(node, sptree, events): - """ Returns the recoliation gene tree with a provided species - topology """ - - if len(node.children) == 2: - # First visit childs - morphed_childs = [] - for ch in node.children: - mc, ev = get_reconciled_tree(ch, sptree, events) - morphed_childs.append(mc) - - # morphed childs are the reconciled children. I trust its - # topology. Remember tree is visited on recursive post-order - sp_child_0 = morphed_childs[0].get_species() - sp_child_1 = morphed_childs[1].get_species() - all_species = sp_child_1 | sp_child_0 - - # If childs represents a duplication (duplicated species) - # Check that both are reconciliated to the same species - if len(sp_child_0 & sp_child_1) > 0: - newnode = copy.deepcopy(node) - newnode.up = None - newnode.children = [] - template = _get_expected_topology(sptree, all_species) - # replaces child0 partition on the template - newmorphed0, matchnode = _replace_on_template(template, morphed_childs[0]) - # replaces child1 partition on the template - newmorphed1, matchnode = _replace_on_template(template, morphed_childs[1]) - newnode.add_child(newmorphed0) - newnode.add_child(newmorphed1) - newnode.add_feature("evoltype", "D") - node.add_feature("evoltype", "D") - e = EvolEvent() - e.etype = "D" - e.inparalogs = node.children[0].get_leaf_names() - e.outparalogs = node.children[1].get_leaf_names() - e.in_seqs = node.children[0].get_leaf_names() - e.out_seqs = node.children[1].get_leaf_names() - events.append(e) - return newnode, events - - # Otherwise, we need to reconciliate species at both sides - # into a single partition. - else: - # gets the topology expected by the observed species - template = _get_expected_topology(sptree, all_species) - # replaces child0 partition on the template - template, matchnode = _replace_on_template(template, morphed_childs[0] ) - # replaces child1 partition on the template - template, matchnode = _replace_on_template(template, morphed_childs[1]) - template.add_feature("evoltype","S") - node.add_feature("evoltype","S") - e = EvolEvent() - e.etype = "S" - e.inparalogs = node.children[0].get_leaf_names() - e.orthologs = node.children[1].get_leaf_names() - e.in_seqs = node.children[0].get_leaf_names() - e.out_seqs = node.children[1].get_leaf_names() - events.append(e) - return template, events - elif len(node.children)==0: - return copy.deepcopy(node), events - else: - raise ValueError("Algorithm can only work with binary trees.") - -def _replace_on_template(orig_template, node): - template = copy.deepcopy(orig_template) - # detects partition within topo that matchs child1 species - nodespcs = node.get_species() - spseed = list(nodespcs)[0] # any sp name woulbe ok - # Set an start point - subtopo = template.search_nodes(children=[], name=spseed)[0] - # While subtopo does not cover all child species - while len(nodespcs - set(subtopo.get_leaf_names() ) )>0: - subtopo= subtopo.up - # Puts original partition on the expected topology template - nodecp = copy.deepcopy(node) - if subtopo.up is None: - return nodecp, nodecp - else: - parent = subtopo.up - parent.remove_child(subtopo) - parent.add_child(nodecp) - return template, nodecp - -def _get_expected_topology(t, species): - missing_sp = set(species) - set(t.get_leaf_names()) - if missing_sp: - raise KeyError("* The following species are not contained in the species tree: "+ ','.join(missing_sp) ) - - node = t.search_nodes(children=[], name=list(species)[0])[0] - - sps = set(species) - while sps-set(node.get_leaf_names()) != set([]): - node = node.up - template = copy.deepcopy(node) - # make get_species() to work - #template._speciesFunction = _get_species_on_TOL - template.set_species_naming_function(_get_species_on_TOL) - template.detach() - for n in [template]+template.get_descendants(): - n.add_feature("evoltype","L") - n.dist = 1 - return template - -def _get_species_on_TOL(name): - return name diff --git a/ete2/phylo/reconciliation.pyc b/ete2/phylo/reconciliation.pyc deleted file mode 100644 index db92df7..0000000 Binary files a/ete2/phylo/reconciliation.pyc and /dev/null differ diff --git a/ete2/phylo/spoverlap.py b/ete2/phylo/spoverlap.py deleted file mode 100644 index 99d13b2..0000000 --- a/ete2/phylo/spoverlap.py +++ /dev/null @@ -1,241 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -from evolevents import EvolEvent - -__all__ = ["get_evol_events_from_leaf", "get_evol_events_from_root"] - -def get_evol_events_from_leaf(node, sos_thr=0.0): - """ Returns a list of duplication and speciation events in - which the current node has been involved. Scanned nodes are - also labeled internally as dup=True|False. You can access this - labels using the 'node.dup' sintaxis. - - Method: the algorithm scans all nodes from the given leafName to - the root. Nodes are assumed to be duplications when a species - overlap is found between its child linages. Method is described - more detail in: - - "The Human Phylome." Huerta-Cepas J, Dopazo H, Dopazo J, Gabaldon - T. Genome Biol. 2007;8(6):R109. - """ - # Get the tree's root - root = node.get_tree_root() - - # Checks that is actually rooted - outgroups = root.get_children() - if len(outgroups) != 2: - raise TypeError, "Tree is not rooted" - - # Cautch the smaller outgroup (will be stored as the tree - # outgroup) - o1 = set([n.name for n in outgroups[0].get_leaves()]) - o2 = set([n.name for n in outgroups[1].get_leaves()]) - - if len(o2) sos_thr:# and d > 0.0: Removed branch control. - event.node = current.up - event.etype = "D" - event.outparalogs = set([n.name for n in sister_leaves if n.species == ref_spcs]) - event.orthologs = set([]) - current.up.add_feature("evoltype","D") - all_events.append(event) - - # If NO species overlap: speciation - elif score == sos_thr: - event.node = current.up - event.etype = "S" - event.orthologs = set([n.name for n in sister_leaves if n.species != ref_spcs]) - event.outparalogs = set([]) - current.up.add_feature("evoltype","S") - all_events.append(event) - else: - pass # do not add event if distances == 0 - - # Updates browsed species - browsed_spcs |= sister_spcs - browsed_leaves |= sister_leaves - sister_leaves = set([]) - # And keep ascending - current = current.up - return all_events - -def get_evol_events_from_root(node, sos_thr): - """ Returns a list of **all** duplication and speciation - events detected after this node. Nodes are assumed to be - duplications when a species overlap is found between its child - linages. Method is described more detail in: - - "The Human Phylome." Huerta-Cepas J, Dopazo H, Dopazo J, Gabaldon - T. Genome Biol. 2007;8(6):R109. - """ - - # Get the tree's root - root = node.get_tree_root() - - # Checks that is actually rooted - outgroups = root.get_children() - if len(outgroups) != 2: - raise TypeError, "Tree is not rooted" - - # Cautch the smaller outgroup (will be stored as the tree outgroup) - o1 = set([n.name for n in outgroups[0].get_leaves()]) - o2 = set([n.name for n in outgroups[1].get_leaves()]) - - - if len(o2)2: - raise TypeError, "nodes are expected to have two childs." - elif len(childs)==0: - pass # leaf - else: - # Get leaves and species at both sides of event - sideA_leaves= set([n for n in childs[0].get_leaves()]) - sideB_leaves= set([n for n in childs[1].get_leaves()]) - sideA_spcs = set([n.species for n in childs[0].get_leaves()]) - sideB_spcs = set([n.species for n in childs[1].get_leaves()]) - # Calculates species overlap - overlaped_spcs = sideA_spcs & sideB_spcs - all_spcs = sideA_spcs | sideB_spcs - score = float(len(overlaped_spcs))/len(all_spcs) - - # Creates a new evolEvent - event = EvolEvent() - event.fam_size = fSize - event.branch_supports = [current.support, current.children[0].support, current.children[1].support] - # event.seed = leafName - # event.e_newick = current.up.get_newick() # high mem usage!! - event.sos = score - event.outgroup_spcs = smaller_outg.get_species() - event.in_seqs = set([n.name for n in sideA_leaves]) - event.out_seqs = set([n.name for n in sideB_leaves]) - event.inparalogs = set([n.name for n in sideA_leaves]) - # If species overlap: duplication - if score >sos_thr: - event.node = current - event.etype = "D" - event.outparalogs = set([n.name for n in sideB_leaves]) - event.orthologs = set([]) - current.add_feature("evoltype","D") - # If NO species overlap: speciation - else: - event.node = current - event.etype = "S" - event.orthologs = set([n.name for n in sideB_leaves]) - event.outparalogs = set([]) - current.add_feature("evoltype","S") - - all_events.append(event) - # Keep visiting nodes - try: - current = to_visit.pop(0) - except IndexError: - current = None - return all_events diff --git a/ete2/phylo/spoverlap.pyc b/ete2/phylo/spoverlap.pyc deleted file mode 100644 index 0798721..0000000 Binary files a/ete2/phylo/spoverlap.pyc and /dev/null differ diff --git a/ete2/phylomedb/__init__.py b/ete2/phylomedb/__init__.py deleted file mode 100644 index 6bfe232..0000000 --- a/ete2/phylomedb/__init__.py +++ /dev/null @@ -1,105 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - - -species_ages = {} - -_humanv1 = { -# Basal eukariotes -"Ath":10, # Arabidopsis thaliana -"Cre":10, -"Pfa":10, -"Pyo":10, -"Ddi":10, -"Gth":10, -"Lma":10, # leismania -"Pte":10, - -# Fungi -"Ago":9, -"Cal":9, -"Cgl":9, -"Cne":9, -"Dha":9, -"Ecu":9, -"Gze":9, -"Kla":9, -"Ncr":9, -"Sce":9, # S.cerevisiae -"Spb":9, -"Yli":9, - -# metazoa non chordates -"Aga":8, # Anopheles -"Dme":8, # Drosophila melanogaster -"Ame":8, # Apis meliferae -"Cel":8, # Caenorabditis elegans -"Cbr":8, # Caenorabditis brigssae - -# chordates non vertebrates -"Cin":7, # Ciona intestinalis - -# vertebrates non tetrapodes -"Dre":6, # Danio rerio -"Tni":6, # Tetraodom -"Fru":6, # Fugu rubripes - -# tetrapodes non birds nor mammals -"Xtr":5, # Xenopus - -# birds -"Gga":4, # Chicken - -# Mammals non primates -"Mdo":3, # Monodelphis domestica -"Mms":3, # Mouse -"Rno":3, # Rat -"Cfa":3, # Dog -"Bta":3, # Cow - -# primates non hominids -"Ptr":2, # chimp -"Mmu":2, # Macaca - -# hominids -"Hsa":1, # human -} -species_ages["human_phylome"] = _humanv1 diff --git a/ete2/phylomedb/__init__.pyc b/ete2/phylomedb/__init__.pyc deleted file mode 100644 index 4afb80c..0000000 Binary files a/ete2/phylomedb/__init__.pyc and /dev/null differ diff --git a/ete2/phylomedb/phylomeDB.py b/ete2/phylomedb/phylomeDB.py deleted file mode 100644 index 72b52c5..0000000 --- a/ete2/phylomedb/phylomeDB.py +++ /dev/null @@ -1,682 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - - -""" -'phylomedb' provides an access API to the data stored in the -phylogenetic database PhylomeDB *[1]. - -All methods to perform queries are implemented within the -PhylomeDBConnector class. - - *[1] PhylomeDB: a database for genome-wide collections of gene - phylogenies Jaime Huerta-Cepas, Anibal Bueno, Joaquin Dopazo and Toni - Gabaldon. - - PhylomeDB is a database of complete phylomes derived for - different genomes within a specific taxonomic range. All - phylomes in the database are built using a high-quality - phylogenetic pipeline that includes evolutionary model testing - and alignment trimming phases. For each genome, PhylomeDB - provides the alignments, phylogentic trees and tree-based - orthology predictions for every single encoded protein. -""" -import re -from string import strip -import MySQLdb -from ete2 import PhyloTree - -__all__ = ["PhylomeDBConnector", "ROOTED_PHYLOMES"] - -# This dictionary sets the default age dictionary (if any) must be -# used to root certain phylome trees. -ROOTED_PHYLOMES = { - 1: { - # Basal eukariotes - "Ath":10, # Arabidopsis thaliana - "Cre":10, - "Pfa":10, - "Pyo":10, - "Ddi":10, - "Gth":10, - "Lma":10, # leismania - "Pte":10, - # Fungi - "Ago":9, - "Cal":9, - "Cgl":9, - "Cne":9, - "Dha":9, - "Ecu":9, - "Gze":9, - "Kla":9, - "Ncr":9, - "Sce":9, # S.cerevisiae - "Spb":9, - "Yli":9, - # metazoa non chordates - "Aga":8, # Anopheles - "Dme":8, # Drosophila melanogaster - "Ame":8, # Apis meliferae - "Cel":8, # Caenorabditis elegans - "Cbr":8, # Caenorabditis brigssae - # chordates non vertebrates - "Cin":7, # Ciona intestinalis - # vertebrates non tetrapodes - "Dre":6, # Danio rerio - "Tni":6, # Tetraodom - "Fru":6, # Fugu rubripes - # tetrapodes non birds nor mammals - "Xtr":5, # Xenopus - # birds - "Gga":4, # Chicken - # Mammals non primates - "Mdo":3, # Monodelphis domestica - "Mms":3, # Mouse - "Rno":3, # Rat - "Cfa":3, # Dog - "Bta":3, # Cow - # primates non hominids - "Ptr":2, # chimp - "Mmu":2, # Macaca - # hominids - "Hsa":1, # human - }, - - # Pea aphid Phylome - 16: { - "Cel" :10, # C.elegans outgroup - "Hsa" :9, # Human outgroup - "Cin" :9, # Ciona outgroup - "Dpu":7, - "Dps":5, - "Tca":5, - "Phu":5, - "Dme":5, - "Api":5, - "Dmo":5, - "Nvi":5, - "Dya":5, - "Aga":5, - "Cpi":5, - "Bom":5, - "Ame":5, - "Aae":5 - } - } - -class PhylomeDBConnector(object): - """ Reuturns a connector to a phylomeDB database. - - ARGUMENTS: - ========== - host: hostname in which phylomeDB is hosted. - user: username to the database. - passwd: password to connect database. - port: port used to connect database. - - RETURNS: - ======== - An object whose methods can be used to query the database. - """ - def __init__(self, host="84.88.66.245", \ - db="phylomeDB", \ - user="public", \ - passwd="public", \ - port=3306): - - """ Connects to a phylomeDB database and returns an object to - perform custom queries on it. """ - - # Reads phylome config file - self._SQLconnection = MySQLdb.connect(host = host,\ - user = user,\ - passwd = passwd,\ - db = db,\ - port = int(port)) - - self._SQL = self._SQLconnection.cursor() - - if user == "phyAdmin": - self._trees_table = "trees" - self._algs_table = "algs" - self._phylomes_table = "phylomes" - else: - self._trees_table = "trees_"+user - self._algs_table = "algs_"+user - self._phylomes_table = "phylomes_"+user - - def _execute_block(self, cmd): - """ Executes a multi-line SQL command and returns the nombre of - affected rows. """ - commands = cmd.split(";") - for c in commands: - c = c.strip() - if c != "": - try: - rows = self._SQL.execute(c+";") - except MySQLdb.Error: - raise - return rows - - # Access API methods - def get_longest_isoform(self, phyID): - """ returns the protID of the """ - - try: - spc_code = phyID[:3] - prot_number = int(phyID[3:]) - except ValueError: - raise ValueError, "invalid phylome protein ID" - else: - cmd = ' SELECT species, IF(gene="" OR gene=NULL,%s,protid) FROM proteins WHERE species="%s" AND (gene,proteome_id)=(SELECT gene, proteome_id FROM proteins WHERE species="%s" AND protid=%s) ORDER BY length(seq) DESC LIMIT 1; ' % (prot_number,spc_code,spc_code,prot_number) - if self._SQL.execute(cmd): - spc,protid = self._SQL.fetchone() - return "%s%07d" % (spc,protid) - else: - return None - - def get_id_by_external(self, external): - """ Returns the phylomeID of the given external ID""" - - command = 'SELECT species,protid from id_conversion where external_id="%s"' % (external) - ids = [] - if self._SQL.execute(command): - matches = self._SQL.fetchall() - # Build phyprotID - for m in matches: - phyID = self.get_longest_isoform("%s%07d" % (m[0],m[1])) - if phyID: - ids.append( phyID ) - return ids - - def get_id_translations(self, seqid): - """ returns all the registered translations of a given seqid """ - - cmd = 'SELECT external_db,external_id from id_conversion where species="%s" and protid=%d' % (seqid[:3],int(seqid[3:])) - conversion = {} - if self._SQL.execute(cmd): - extids = self._SQL.fetchall() - for db, eid in extids: - conversion.setdefault(db, []).append(eid) - return conversion - - def search_id(self, queryID): - """ Returns a list of phylome protein Ids associated to the - given external queryID. If queryID is a phylomeDB id, it - returns the longest isoform associated to the queryID's gene - """ - queryID = queryID.strip() - - # This is to avoid weird queryIDs which make create slow or - # invalid MYSQL queries - QUERYID_GENERAL_REGEXP_FILTER = "^[\w\d\-_,;:.|#@\/\\\()'<>!]+$" - QUERYID_INTERNAL_ID_REGEXP_FILTER = "^\w{3}\d{7}$" - - phyID_matches = [] - # First check if id is a phylomeID - if re.match(QUERYID_INTERNAL_ID_REGEXP_FILTER, queryID): - phyID = self.get_longest_isoform(queryID) - phyID_matches.append(phyID) - - elif re.match(QUERYID_GENERAL_REGEXP_FILTER, queryID): - # Second checks if id is the original name or gene for of a phylome ID - cmd = 'SELECT species,protid from proteins where name="%s" or gene="%s"' % (queryID,queryID) - if self._SQL.execute(cmd): - for spc_code, protid in self._SQL.fetchall(): - phyID = self.get_longest_isoform("%s%07d" % (spc_code,protid)) - phyID_matches.append( phyID ) - - # Last checks if id is in the id conversion table and adds the resulting mathes - hits = self.get_id_by_external(queryID) - if hits: - phyID_matches.extend(hits) - - return phyID_matches - - def get_proteomes(self): - """ Returns all current available proteomes""" - cmd = 'SELECT * FROM proteomes' - if self._SQL.execute(cmd): - return self._SQL.fetchall() - - def get_species(self): - """ Returns all current available species""" - - cmd = 'SELECT * FROM species' - if self._SQL.execute(cmd): - return self._SQL.fetchall() - def get_phylomes(self): - """ Returns all current available phylomes """ - cmd = 'SELECT phylome_id,seed_proteome,proteomes,DATE(ts),name,description,comments FROM %s' %(self._phylomes_table) - phylomes = {} - if self._SQL.execute(cmd): - for phylo in self._SQL.fetchall(): - phylome_id = phylo[0] - phylomes[phylome_id]={} - phylomes[phylome_id]["seed_proteome"] = phylo[1] - phylomes[phylome_id]["seed_species"] = phylo[1][:3] - phylomes[phylome_id]["proteomes"] = phylo[2] - phylomes[phylome_id]["name"] = phylo[4] - phylomes[phylome_id]["description"] = phylo[5] - phylomes[phylome_id]["date"] = phylo[3] - phylomes[phylome_id]["comments"] = phylo[6] - return phylomes - - def get_proteomes_in_phylome(self,phylome_id): - """ Returns a list of proteomes associated to a given phylome_id""" - - cmd = 'SELECT proteomes FROM %s WHERE phylome_id="%s" ' \ - % (self._phylomes_table, phylome_id) - self._SQL.execute(cmd) - entries = self._SQL.fetchone() - if entries: - proteomes_string = map(strip, entries[0].split(",")) - else: - proteomes_string = None - return proteomes_string - - def get_seqids_in_proteome(self, proteome_id, filter_isoforms=True): - """ Returns all sequences of a given proteome """ - - seqids = [] - if filter_isoforms: - cmd = 'SELECT species,protid,gene,seq FROM proteins WHERE proteome_id="%s" AND species="%s" ' \ - % (proteome_id[3:],proteome_id[:3]) - if self._SQL.execute(cmd): - entries = self._SQL.fetchall() - largest_isoforms = {} - unknown_counter = 0 - for spcs,protid,gene,seq in entries: - gene = gene.strip() - unknown_counter += 1 - if not gene: - gene="phyunknown%d" % unknown_counter - unknown_counter += 1 - if gene not in largest_isoforms: - largest_isoforms[gene] = (spcs,protid,gene,seq) - elif len(seq) > len(largest_isoforms[gene][3]): - largest_isoforms[gene] = (spcs,protid,gene,seq) - seqids = ["%s%07d"%(v[0], v[1]) for v in largest_isoforms.values()] - else: - cmd = 'SELECT species,protid FROM proteins WHERE proteome_id="%s" AND species="%s" ' \ - % (proteome_id[3:],proteome_id[:3]) - if self._SQL.execute(cmd): - seqids = ["%s%07d"%(spc,protid) for spc,protid in self._SQL.fetchall()] - - return seqids - - def get_seqs_in_proteome(self, proteome_id, filter_isoforms=True): - cmd = 'SELECT species,protid,gene,seq FROM proteins WHERE proteome_id="%s" AND species="%s" ' \ - % (proteome_id[3:],proteome_id[:3]) - if self._SQL.execute(cmd): - entries = self._SQL.fetchall() - if filter_isoforms: - largest_isoforms = {} - unknown_counter = 0 - for spcs,protid,gene,seq in entries: - gene = gene.strip() - unknown_counter += 1 - if not gene: - gene="phyunknown%d" % unknown_counter - unknown_counter += 1 - if gene not in largest_isoforms: - largest_isoforms[gene] = (spcs,protid,gene,seq) - elif len(seq) > len(largest_isoforms[gene][3]): - largest_isoforms[gene] = (spcs,protid,gene,seq) - seqs = largest_isoforms.values() - else: - seqs = entries - else: - seqs = None - - return seqs - - def get_proteome_info(self,proteome_id): - """ Returns all info about a registered proteome""" - - cmd = 'SELECT proteome_id,species,source,comments,date FROM proteomes WHERE proteome_id ="%s" AND species="%s" ' \ - % (proteome_id[3:],proteome_id[:3]) - info = {} - if self._SQL.execute(cmd): - entry = self._SQL.fetchone() - info["proteome_id"] = entry[0] - info["species"] = entry[1] - info["source"] = entry[2] - info["comments"] = entry[3] - info["date"] = entry[4] - return info - - def get_seqid_info(self, protid): - """ Returns orginal info about a given protid""" - cmd = 'SELECT species,protid,proteome_id,name,gene,comments,seq FROM proteins WHERE species="%s" and protid="%s"' \ - % (protid[:3],protid[3:]) - - info = {} - if self._SQL.execute(cmd): - entry = self._SQL.fetchone() - info["species"] = entry[0] - info["seqid"] = entry[1] - info["proteome_id"] = entry[2] - info["name"] = entry[3] - info["gene"] = entry[4] - info["comments"] = entry[5] - info["seq"] = entry[6] - return info - - def get_phylome_info(self, phylomeid): - """ Returns info on a given phylome""" - cmd = 'SELECT seed_proteome,proteomes,DATE(ts),name,description,comments FROM %s WHERE phylome_id="%s" ' %\ - (self._phylomes_table, phylomeid) - info = {} - if self._SQL.execute(cmd): - all_info = self._SQL.fetchone() - info["id"] = int(phylomeid) - info["seed_proteome"] = all_info[0] - info["seed_species"] = all_info[0][:3] - info["proteomes"] = all_info[1] - info["name"] = all_info[3] - info["description"] = all_info[4] - info["date"] = all_info[2] - info["comments"] = all_info[5] - return info - - def get_species_info(self, taxid_or_code): - """ Returns all information on a given species_code""" - - command = 'SELECT taxid,code,name from species where taxid="%s"' % (taxid_or_code) - if self._SQL.execute(command): - return self._SQL.fetchone() - else: - command = 'SELECT taxid,code,name from species where code="%s"' % (taxid_or_code) - info = {} - if self._SQL.execute(command): - entry = self._SQL.fetchone() - info["taxid"] = entry[0] - info["code"] = entry[1] - info["name"] = entry[2] - return info - - def get_seed_ids(self, phylome_id, filter_isoforms=True): - # WORKS VERY SLOW !! - cmd = 'SELECT seed_proteome FROM %s WHERE phylome_id="%s";' % (self._phylomes_table, phylome_id) - if self._SQL.execute(cmd): - seed_proteome = self._SQL.fetchone()[0] - seedids = self.get_seqids_in_proteome(seed_proteome, filter_isoforms=filter_isoforms) - else: - seedids = [] - return seedids - - def get_collateral_seeds(self, seqid): - cmd = 'SELECT seed_id, phylome_id FROM seed_friends WHERE species="%s" and protid="%s";' %\ - (seqid[:3],int(seqid[3:])) - if self._SQL.execute(cmd): - return self._SQL.fetchall() - else: - return [] - - def get_available_trees(self, seqid, collateral=True): - trees = {seqid:{}} - cmd = 'SELECT phylome_id, method FROM %s WHERE species="%s" AND protid="%s" ' \ - %(self._trees_table, seqid[:3], seqid[3:]) - if self._SQL.execute(cmd): - for phylome_id, method in self._SQL.fetchall(): - if phylome_id in trees[seqid]: - trees[seqid][phylome_id].append(method) - else: - trees[seqid][phylome_id] = [method] - - if collateral: - for cseed, phyid in self.get_collateral_seeds(seqid): - cmd = 'SELECT method FROM %s WHERE species="%s" AND protid="%s" and phylome_id ="%s" ' \ - %(self._trees_table, cseed[:3], cseed[3:], phyid) - if self._SQL.execute(cmd): - trees[cseed] = {} - trees[cseed][phyid] = [method[0] for method in self._SQL.fetchall()] - return trees - - def get_available_trees_by_phylome(self, seqid, collateral=True): - trees = {seqid:{}} - cmd = 'SELECT phylome_id, method FROM %s WHERE species="%s" AND protid="%s" ' \ - %(self._trees_table, seqid[:3], seqid[3:]) - - phyid2trees = {} - if self._SQL.execute(cmd): - for phylome_id, method in self._SQL.fetchall(): - if phylome_id not in phyid2trees: - phyid2trees[phylome_id] = {seqid: [method]} - elif seqid in phyid2trees[phylome_id]: - phyid2trees[phylome_id][seqid].append(method) - elif seqid not in phyid2trees[phylome_id]: - phyid2trees[phylome_id][seqid] = [method] - - if collateral: - for cseed, phyid in self.get_collateral_seeds(seqid): - cmd = 'SELECT method FROM %s WHERE species="%s" AND protid="%s" and phylome_id ="%s" ' \ - %(self._trees_table, cseed[:3], cseed[3:], phyid) - if self._SQL.execute(cmd): - phyid2trees.setdefault(phyid, {})[cseed] = [method[0] for method in self._SQL.fetchall()] - - return phyid2trees - - def get_available_trees_in_phylome(self, seqid, phylomeid): - trees = {seqid:{}} - cmd = 'SELECT method, lk FROM %s WHERE species="%s" AND protid="%s" AND phylome_id=%s' \ - %(self._trees_table, seqid[:3], seqid[3:], phylomeid) - if self._SQL.execute(cmd): - return dict(self._SQL.fetchall()) - else: - return {} - - def get_tree(self, protid, method, phylome_id): - """ Returns the method-tree associated to a given protid. """ - - cmd = 'SELECT newick,lk FROM %s WHERE phylome_id=%s AND species="%s" AND protid="%s" AND method ="%s"' %\ - (self._trees_table, phylome_id, protid[:3],protid[3:],method) - if self._SQL.execute(cmd): - entry = self._SQL.fetchone() - nw = entry[0] - lk = float(entry[1]) - t = PhyloTree(nw) - else: - t = None - lk = None - return t,lk - def get_best_tree(self, protid, phylome_id): - """ Returns the winner ML tree""" - - likelihoods = {} - winner_model = None - winner_lk = None - winner_newick = None - t = None - command ='SELECT newick,method,lk FROM %s WHERE phylome_id=%s AND species="%s" and protid="%s";' \ - % (self._trees_table,phylome_id, protid[:3], protid[3:]) - self._SQL.execute(command) - result = self._SQL.fetchall() - for r in result: - nw,m,lk = r - if lk < 0: - likelihoods[m] = lk - if winner_lk==None or lk > winner_lk: - winner_lk = lk - winner_model = m - winner_newick = nw - if winner_newick: - t = PhyloTree(winner_newick) - return winner_model,likelihoods,t - def get_algs(self, protid, phylome_id): - """ Given a protID, it returns a tuple with the raw_alg, clean_alg and - the number of seqs included. - """ - - command = 'SELECT raw_alg,clean_alg,seqnumber FROM %s WHERE phylome_id=%s AND species="%s" AND protid="%s"' %\ - (self._algs_table, phylome_id, protid[:3],protid[3:]) - self._SQL.execute(command) - return self._SQL.fetchone() - - def get_raw_alg(self, protid, phylome_id): - """ Given a protID, it returns a tuple with the raw_alg and - the number of seqs included. - """ - - command = 'SELECT raw_alg,seqnumber FROM %s WHERE phylome_id=%s AND species="%s" AND protid="%s"' %\ - (self._algs_table, phylome_id, protid[:3],protid[3:]) - if self._SQL.execute(command): - return self._SQL.fetchone() - - def get_clean_alg(self, protid, phylome_id): - """ Given a protID, it returns a tuple with the clean_alg and - the number of seqs included. - """ - - command = 'SELECT clean_alg,seqnumber FROM %s WHERE phylome_id=%s AND species="%s" AND protid="%s"' %\ - (self._algs_table, phylome_id, protid[:3],protid[3:]) - if self._SQL.execute(command): - return self._SQL.fetchone() - - - def get_phylome_trees(self, phylomeid): - cmd = 'SELECT species, protid, method from %s where phylome_id=%s' \ - %(self._trees_table,phylomeid) - method2seqid = {} - if self._SQL.execute(cmd): - for sp, protid, method in self._SQL.fetchall(): - method2seqid.setdefault(method, []).append("%s%07d" %(sp, protid)) - return method2seqid - def get_phylome_algs(self, phylomeid): - cmd = 'SELECT species, protid from %s where phylome_id =%s' \ - %(self._algs_table, phylomeid) - if self._SQL.execute(cmd): - return self._SQL.fetchall() - else: - return () - - def count_trees(self, phylomeid): - cmd = 'SELECT method,count(*) from %s where phylome_id=%s GROUP BY method' \ - %(self._trees_table,phylomeid) - counter = {} - if self._SQL.execute(cmd): - for method, n in self._SQL.fetchall(): - counter[method] = n - return counter - - def count_algs(self, phylomeid): - cmd = 'SELECT count(*) from %s where phylome_id=%s;' \ - %(self._algs_table,phylomeid) - if self._SQL.execute(cmd): - return self._SQL.fetchone()[0] - else: - return 0 - - def get_orthologs(self, seqid, sp2age=None): - """ Returns the orthology predictions of the given seqid in all - phylomes. - - Only seed trees will be used to detect orthologies, and trees will - be rooted as the default policy defined in the API. If phylome has - an asociated dictionary of species ages, - root_to_farthest_oldest_leaf algorithm will be applied. Otherwise, - midpoint is used. - - You can also provide your own species age dictionary to force the - rooting of the trees according to such data. - - - ARGUMENTS: - ========== - - seqid: the ID of a sequence in the phylomeDB format. - i.e. Hsa0000001 - - sp2age: a dictionary of species code ages (key=species_code, - value=age). i.e. {"Hsa":1, "Dme":4, "Ath":10} - - RETURNS: - ========= - - A dictionary of orthologs and inparalogs found in each scanned - phylomes. - - """ - phylome2or = {} - if type(seqid) == str: - seqid = [seqid] - for sid in seqid: - avail_trees = self.get_available_trees(sid) - for seedid, phylomes in avail_trees.iteritems(): - if seedid != sid: - continue # Skips collateral trees!! - for phyid in phylomes: - # Get the tree for each seed id - method, lks, t = self.get_best_tree(seedid, phyid) - # Roots the tree according to a predefined criterion - if sp2age is not None: - outgroup = t.get_farthest_oldest_leaf(sp2age) - t.set_outgroup(outgroup) - elif phyid in ROOTED_PHYLOMES: - outgroup = t.get_farthest_oldest_leaf( ROOTED_PHYLOMES[phyid] ) - t.set_outgroup(outgroup) - else: - t.set_outgroup(t.get_midpoint_outgroup()) - - # Catches the node for our id (not necesarily the - # seedid) and obtains its evol events - seed_node = t.get_leaves_by_name(sid)[0] - evol_events = seed_node.get_my_evol_events() - # Predictions are sorted by species. - sp2or = {} - sp2in = {} - or2in = {} - for e in filter(lambda x: x.etype=="S", evol_events): - for o in e.orthologs: - sp = o[:3] - # orthologs sorted by species - sp2or.setdefault(sp, set([])).add(o) - - # inparalogs sorted by orthologs - or2in.setdefault(o, set([])).update(e.inparalogs) - - # inparalogs sorted by orthologs - sp2in.setdefault(sp, set([])).update(e.inparalogs) - - phylome2or[phyid] = [sp2or, sp2in, or2in] - return phylome2or diff --git a/ete2/phylomedb/phylomeDB3.py b/ete2/phylomedb/phylomeDB3.py deleted file mode 100644 index aecc74e..0000000 --- a/ete2/phylomedb/phylomeDB3.py +++ /dev/null @@ -1,1506 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - - -""" -'phylomeDB3' provides an access API to the data stored in the phylogenetic -database PhylomeDB *[1][2]. - -Methods to perform queries are implemented within the PhylomeDB3Connector class. - - *[1] PhylomeDB: a database for genome-wide collections of gene phylogenies. - Jaime Huerta-Cepas, Anibal Bueno, Joaquin Dopazo and Toni Gabaldon. - Nucleic acids research (database issue). 2008. - - *[2] PhylomeDB v3.0: an expanding repository of genome-wide collections of - trees, alignments and phylogeny-based orthology and paralogy predictions. - Jaime Huerta-Cepas, Salvador Capella-Gutierrez, Leszek P. Pryszcz, Ivan - Denisov, Diego Kormes, Marina Marcet-Houben and Toni Gabaldon T. - Nucleic acids research (database issue). 2010. - - PhylomeDB is a database of complete phylomes derived for different genomes - within a specific taxonomic range. All phylomes in the database are built - using a high-quality phylogenetic pipeline that includes evolutionary - model testing and alignment trimming phases. For each genome, PhylomeDB - provides the alignments, phylogentic trees and tree-based orthology - predictions for every single encoded protein. -""" -import re -import MySQLdb -from string import strip -from ete2 import PhyloTree - -def extract_species_name(name): - return name.split("_")[1] - -ID_PATTERN = re.compile("^[Pp][Hh][Yy]\w{7}(_\w{2,7})?$") -ITERABLE_TYPES = set([list, set, tuple, frozenset]) - -__all__ = ["PhylomeDB3Connector"] - - -class Phylome(object): - def __str__(self): - info = "Phylome %s (%s)\n" %(self.phyid,self.name) +\ - " seed species: %s\n" %(self.tax2name[self.seed_taxid]) +\ - " seed proteome: %s\n" %(self.seed_proteome) +\ - " Species: %d\n" %len(self.species) +\ - " Seed sequences: %d\n" %len(self.seed_ids) +\ - " Trees: %d\n" %len(self.trees) +\ - " Proteome list: %s\n" %','.join(self.proteomes) - return info - - def __init__(self, phyid, connector, filter_isoforms=True): - self.filter_isoforms = filter_isoforms - self._conn = connector - self._dsql = connector.cursor(MySQLdb.cursors.DictCursor) - self._lsql = connector.cursor(MySQLdb.cursors.Cursor) - - # Get seed ids - cmd = 'SELECT seed_taxid, seed_version, name, description, comments FROM phylome' +\ - ' WHERE phylome_id = %s' % (phyid) - self._dsql.execute(cmd) - phyinfo = self._dsql.fetchone() - self.phyid = phyid - self.seed_taxid = phyinfo["seed_taxid"] - self.prot_vs = phyinfo["seed_version"] - self.name = phyinfo["name"] - self.description = phyinfo["description"] - # Phylome content - cmd = 'SELECT taxid, version FROM phylome_content' +\ - ' WHERE phylome_id = %s' % (phyid) - self._lsql.execute(cmd) - phycontent = self._lsql.fetchall() - self.species = [int(e[0]) for e in phycontent] - - # Species info - cmd = 'SELECT taxid, code, name FROM species' +\ - ' WHERE taxid IN (%s);' %','.join(map(str, self.species)) - self._lsql.execute(cmd) - sp_info = self._lsql.fetchall() - self.tax2name = {} - self.tax2code = {} - self.code2tax = {} - for taxid, code, name in sp_info: - self.tax2name[taxid] = name - self.tax2code[taxid] = code - self.code2tax[code] = taxid - self.proteomes = [self.tax2code[e[0]]+str(e[1]) for e in phycontent] - self.seed_proteome = "%s%d" %(self.tax2code[self.seed_taxid], self.prot_vs) - - # Seed ids - if self.filter_isoforms: - cmd = 'SELECT DISTINCT CONCAT("Phy", i.longest, "_", s.code) AS protid ' - cmd += 'FROM protein AS p, isoform AS i, species AS s WHERE p.taxid = ' - cmd += '%s AND p.version = %s AND p.protid = i.isoform' % (self.seed_taxid, self.prot_vs) - cmd += ' AND p.version = i.version AND p.taxid = s.taxid' - else: - cmd = 'SELECT DISTINCT CONCAT("Phy", protid, "_", code) AS protid FROM ' - cmd += 'protein AS p, species AS s WHERE p.taxid = %s AND p.' % (self.seed_taxid) - cmd += 'version = %s AND p.taxid = s.taxid' % (self.prot_vs) - - self._lsql.execute(cmd) - self.seed_ids = [e[0] for e in self._lsql.fetchall()] - self.load_trees() - - def load_trees(self, seqnames=None, model="best_lk", anotate_trees = True): - """ - Returns all newick tree for the given set of seqnames and - model. If no seqnames are provided, all available trees in the - phylome is returned. - """ - def clean_name(name): - quote = lambda x: '"%s"' %x - m = re.search("Phy(\w{7})_[\w\d]+", name) - if m: - return quote(m.groups()[0]) - - if not seqnames: - seqids = map(clean_name, self.seed_ids) - else: - seqids = map(clean_name, seqnames) - - tree_table = "tree" - cmd = 'SELECT temp.protid, temp.method, temp.lk, temp.newick from ' +\ - ' (SELECT T.protid , T.method, T.newick, T.lk FROM %s AS T WHERE' %(tree_table) +\ - ' T.phylome_id = %s AND T.protid IN (%s)' %(self.phyid, ','.join(seqids)) +\ - ' ORDER BY lk DESC) AS temp GROUP BY protid; ' - - self.trees = {} - if self._lsql.execute(cmd): - seed_code = self.tax2code[self.seed_taxid] - for protid, method, lk, nw in self._lsql.fetchall(): - seqid = "Phy%s_%s" %(protid, seed_code) - self.trees[seqid] = [nw, method, lk] - #t.add_features(lk=lk, method=method) - - def get_algs(self, seqid, atype="clean"): - pass - - def get_seed_species(self): - pass - - -class PhylomeDB(object): - def __init__(self, host = "84.88.66.245", db = "phylomedb_3", user = "public", - passwd = "public", port = 3306): - """ Connect to a phylomeDB database and return an object to perform queries - to the database. - """ - # Establish the connection to the MySQL database where phylomeDB is stored. - try: - self._SQLconnection = MySQLdb.connect(host = host, user = user, passwd = \ - passwd, db = db, port = int(port)) - except: - raise NameError("ERROR: Check your connection parameters") - - self._SQL = self._SQLconnection.cursor(MySQLdb.cursors.DictCursor) - - # Store the connection parameters to use it if the connection is lost. - self.db = db - self.host = host - self.user = user - self.port = port - self.passwd = passwd - - # Define the different database views depending on the user profile - self._trees = "tree_public" - self._algs = "alignment_public" - self._phylomes = "phylome_public" - self._phy_content = "phycontent_public" - - def get_phylome(self, phyid): - pass - - def get_proteomes(self, protids=[]): - pass - - def get_seqs(self, seqids=[]): - 'get aa sequence of seqids' - pass - - def search_trees(self, seqid, include_collateral=True): - 'Returns all available trees for seqid' - pass - - - - - - -class PhylomeDB3Connector(object): - """ Returns a connector to a phylomeDB3 database. - - ARGUMENTS: - ========== - db: database name in the host server. - host: hostname in which phylomeDB is hosted. - user: username to the database. - port: port used to connect database. - passwd: password to connect database. - - RETURNS: - ======== - An object whose methods can be used to query the database. - """ - - ######### - def _get_phylome(self, phyid): - return Phylome(phyid, connector = self._SQLconnection) - - ########## - - def __init__(self, host = "84.88.66.245", db = "phylomedb_3", user = "public", - passwd = "public", port = 3306): - """ Connect to a phylomeDB database and return an object to perform queries - to the database. - """ - - # Establish the connection to the MySQL database where phylomeDB is stored. - try: - self._SQLconnection = MySQLdb.connect(host = host, user = user, passwd = \ - passwd, db = db, port = int(port)) - except: - raise NameError("ERROR: Check your connection parameters") - - self._SQL = self._SQLconnection.cursor(MySQLdb.cursors.DictCursor) - - # Store the connection parameters to use it if the connection is lost. - self.db = db - self.host = host - self.user = user - self.port = port - self.passwd = passwd - - # Define the different database views depending on the user profile - self._trees = "tree_public" - self._algs = "alignment_public" - self._phylomes = "phylome_public" - self._phy_content = "phycontent_public" - - def __execute__(self, command): - """ Check whether a given connection is still open or not. If the connection - has been closed by the server, try to recover it. Then, execute the - input MySQL query - """ - - ## Try to either refresh an open cursor or reconnect to the database. - try: - self._SQL = self._SQLconnection.cursor(MySQLdb.cursors.DictCursor) - except: - try: - self._SQLconnection = MySQLdb.connect(host = self.host, db = self.db, \ - user = self.user, passwd = self.passwd, port = int(self.port)) - except: - raise NameError("ERROR: Impossible to reconnect to the database") - else: - self._SQL = self._SQLconnection.cursor(MySQLdb.cursors.DictCursor) - - ## If it is possible to get a cursor, execute the command - return self._SQL.execute(command) - - def __execute_block__(self, commands): - """ Executes a multi-line MySQL query - """ - - ## Retrieve the different MySQL lines and split it in an appropiate way - for query in [l for l in map(strip, commands.split(";")) if l]: - if not self.__execute__(query): - raise NameError("__execute_block__ An error occurred during a MySQL op") - - def __fomat_MySQL_to_dict__(self, index, dict): - """ Takes as an input the result of a MySQL query and returns a dictionary - using as a key one of the values from the MySQL results - """ - - ## Check whether the input data has the appropiate format - ## Check as well if the key is present inside of each dict - if type(dict) != tuple: - msg = "__format_MySQL_to_dict__ Check the input structure datatype. " - raise NameError(("%s It should be a 'tuple'") % (msg)) - for entry in dict: - if not index in entry: - raise NameError("__format_MySQL_to_dict__ Define the index") - - formatted_dict = {} - ## Format the input data - for entry in dict: - formatted_dict[entry[index]] = entry - del formatted_dict[entry[index]][index] - return formatted_dict - - def __parser_ids__(self, ids): - """ Returns a string with the input id/s ready to be used in any MySQL query - """ - if not ids: - raise NameError(("__parser_ids__: Check your input data '%s'") % str(ids)) - # Define a function to manage the different ids - parser = lambda id: id[3:10] if ID_PATTERN.match(id) else None - - ids = [ids] if type(ids) == str else ids - ## If the ids belongs to one of the predefined iterable types, - ## try to convert each member in a valid phylomeDB code - if type(ids) in ITERABLE_TYPES: - parsed = ', ' .join(['"%s"' % parser(n) for n in ids if parser(n)]) - return parsed if parsed else None - - raise NameError(("__parser_ids__: Check your input data '%s'") % str(ids)) - - def __check_input_parameter__(self, **kargs): - """ Check the different input parameters - """ - - ## Define the available checks - valid_keys = set(["str_number", "single_id", "list_id", "code", "string", \ - "boolean", "number"]) - - ## Check that all input keys have associated an verification clause - if set(kargs) - valid_keys != set(): - raise NameError("check_input_parameter: Invalid datatype") - - ## Check whether all input parameters has a value - ## Although it is permitted for some 'keys' have 'None' as a value - for key in kargs: - if key not in ["number", "string"] and not kargs[key]: - if kargs[key] not in [0, "", False]: - return False - - ## Check whether the value is either a positive integer number - if "number" in kargs: - if kargs["number"]: - if not str(kargs["number"]).isdigit() or str(kargs["number"]) == "0": - return False - ## ... or a integer number greater or equal to zero - if "str_number" in kargs and not str(kargs["str_number"]).isdigit(): - return False - ## ... or a boolean number - if "boolean" in kargs and type(kargs["boolean"]) != bool: - return False - - ## Check whether the input parameter should be an single phylomeDB ID - if "single_id" in kargs: - if not self.__parser_ids__(kargs["single_id"]) or \ - type(kargs["single_id"]) != str: - return False - ## ... or it could be a list of, at least, phylomeDB IDs - if "list_id" in kargs and not self.__parser_ids__(kargs["list_id"]): - return False - - ## Check if a single string has been given as an input parameter - if "string" in kargs: - if kargs["string"]: - if type(kargs["string"]) != str or len(kargs["string"].split()) > 1: - return False - - ## Return true if and only if all input parameters are well-constructed - return True - - def get_external_ids(self, ids): - """ Returns all the external IDs registered in the 'external_id' table that - are associated to the input phylomeDB IDs - """ - - ids = self.__parser_ids__(ids) - cmd = 'SELECT DISTINCT CONCAT("Phy", p.protid, "_", s.code) as protid, ' - cmd += 'external_db AS db, external_id AS id FROM protein AS p, species AS ' - cmd += 's, external_id AS ex WHERE p.protid IN (%s) AND p.taxid = ' % (ids) - cmd += 's.taxid AND p.protid = ex.protid' - - external_ids = {} - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - external_ids.setdefault(row["protid"], {}) - external_ids[row["protid"]].setdefault(row["db"], set()).add(row["id"]) - - for protid in external_ids: - for key in external_ids[protid]: - external_ids[protid][key] = list(external_ids[protid][key]) - - return external_ids - - def get_go_ids(self, ids): - """ Returns all available GO Terms associated to the input phylomeDB IDs - """ - - ids = self.__parser_ids__(ids) - cmd = 'SELECT DISTINCT CONCAT("Phy", p.protid, "_", s.code) as protid, ' - cmd += 'external_db AS db, CONCAT("GO:", go_term) AS go FROM protein AS p, ' - cmd += 'species AS s, go WHERE p.protid IN (%s) AND p.taxid = s.' % (ids) - cmd += 'taxid AND p.protid = go.protid' - - external_ids = {} - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - external_ids.setdefault(row["protid"], {}) - external_ids[row["protid"]].setdefault(row["db"], set()).add(row["go"]) - - for protid in external_ids: - for key in external_ids[protid]: - external_ids[protid][key] = list(external_ids[protid][key]) - - return external_ids - - def get_old_phylomedb_ids(self, ids): - """ Returns all old phylomeDB IDs associated to each of the input phylomeDB - IDs - """ - - ids = self.__parser_ids__(ids) - cmd = 'SELECT DISTINCT CONCAT("Phy", p.protid, "_", s.code) as protid, ' - cmd += 'CONCAT(old_code, LPAD(old_protid, 7, "0")) AS old_code FROM protein' - cmd += ' AS p, species AS s, old_protein AS old WHERE p.protid IN ' - cmd += '(%s) AND p.taxid = s.taxid AND p.protid = old.protid' % (ids) - - old_ids = {} - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - old_ids.setdefault(row["protid"], {}).setdefault("old_phylomedb", set()) - old_ids[row["protid"]]["old_phylomedb"].add(row["old_code"]) - - for protid in old_ids: - for key in old_ids[protid]: - old_ids[protid][key] = list(old_ids[protid][key]) - - return old_ids - - def get_prot_gene_names(self, ids): - """ Returns all possible protein and gene names associated to the input - phylomeDB IDs - """ - - ids = self.__parser_ids__(ids) - cmd = 'SELECT DISTINCT CONCAT("Phy", p.protid, "_", s.code) as protid, ' - cmd += 'prot_name, gene_name FROM protein AS p, species AS s WHERE p.protid' - cmd += ' IN (%s) AND p.taxid = s.taxid' % (ids) - - name = {} - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - if row["prot_name"]: - name.setdefault(row["protid"], {}).setdefault("protein_name", set()) - name[row["protid"]]["protein_name"].add(row["prot_name"]) - if row["gene_name"]: - name.setdefault(row["protid"], {}).setdefault("gene_name", set()) - name[row["protid"]]["gene_name"].add(row["gene_name"]) - - for protid in name: - for key in name[protid]: - name[protid][key] = list(name[protid][key]) - - return name - - def get_new_phylomedb_id(self, old_id): - """ Return the conversion between an old phylomeDB ID and a new one - """ - - # Check whether the input code is a valid former phylomeDB id or not - QUERY_OLD_REGEXP_FILTER = "^\w{3}\d{1,}$" - if not re.match(QUERY_OLD_REGEXP_FILTER, old_id): - return None - - # Look if the given code can be mapped into the phylomeDB dabatase - cmd = 'SELECT CONCAT("Phy", p.protid, "_", s.code) as protid FROM old_' - cmd += 'protein AS p, species AS s WHERE (s.taxid = p.taxid AND p.old_code ' - cmd += '= "%s" AND p.old_protid = %s)' % (old_id[:3], old_id[3:]) - - if self.__execute__(cmd): - return self._SQL.fetchone()["protid"] - return None - - def get_info_homologous_seqs(self, protid, phylome_id, tree = None, \ - tree_method = False, sequence = False): - """ Return all the available information for a given set of homologous - sequences extracted from a tree from a given phylome. - """ - - ## Depending on the input parameters, recover the best tree for the - ## input phylomeDB ID in the input phylomeDB. Otherwise, the function - ## will try to recover the tree reconstructed under the model specific - data = {} - - if tree == None: - tree_db = self.get_tree(protid, phylome_id, best_tree = True) - - elif tree and not tree_method: - tree_db = self.get_tree(protid, phylome_id, best_tree = True) - - elif tree and tree_method: - tree_db = self.get_tree(protid, phylome_id, method = tree_method) - - ## Check whether it has been possible to recover a tree from the database - if not tree_db: - return data - else: - method = tree_db.keys()[0] - - ## If it has been required, store the tree in an appropiate data structure. - if tree: - data.setdefault("tree", {}) - data["tree"]["method"] = method - data["tree"]["lk"] = tree_db[method]["lk"] - data["tree"]["tree"] = tree_db[method]["tree"] - data["tree"]["best"] = True if not tree_method else False - - ## Recover the leaf names taking into account that there is information - ## associated to the sequence while there is another information associated - ## for each copy of the sequence. - leaves = tree_db[method]["tree"].get_leaf_names() - ids = set(["_".join(name.split("_")[:2]) for name in leaves]) - protids = self.__parser_ids__(ids) - - ## Establish whether the tree contains more than one copy for each sequence - ## and if the tree leaf names reflect that situation or not - copy_var_support = True if len(leaves) == len(set(leaves)) else False - - ## Join and retrieve all the information available in the database for the - ## unique sequences in the set - cmd = 'SELECT CONCAT("Phy", p.protid, "_", s.code) AS protid, s.code, CONC' - cmd += 'AT(s.code, ".", p.version) AS proteome, p.taxid, p.version, s.name,' - cmd += ' MAX(copy) AS copy, count(DISTINCT method) AS trees, count(DISTINCT' - cmd += ' sf.protid, sf.phylome_id) AS collat FROM (protein AS p, species AS' - cmd += ' s, %s AS ph, %s AS pc) LEFT ' % (self._phylomes,self._phy_content) - cmd += 'JOIN %s AS t ON (p.protid = t.protid) LEFT JOIN ' % (self._trees) - cmd += 'seed_friend AS sf ON (p.protid = sf.friend_id) WHERE (p.protid IN ' - cmd += '(%s) AND p.taxid = s.taxid AND p.taxid = ' % (protids) - cmd += 'pc.taxid AND pc.phylome_id = %s AND ph.phylome_id = ' % (phylome_id) - cmd += 'pc.phylome_id AND pc.version = p.version) GROUP BY p.protid' - - if self.__execute__(cmd): - data.setdefault("seq", {}) - for row in self._SQL.fetchall(): - data["seq"].setdefault(row["protid"], {}) - - data["seq"][row["protid"]]["copy"] = row["copy"] - data["seq"][row["protid"]]["trees"] = row["trees"] - data["seq"][row["protid"]]["taxid"] = row["taxid"] - data["seq"][row["protid"]]["proteome"] = row["proteome"] - data["seq"][row["protid"]]["collateral"] = row["collat"] - data["seq"][row["protid"]]["species_name"] = row["name"] - data["seq"][row["protid"]]["species_code"] = row["code"] - - ## In some cases, it is necessary as well to recover the protein sequence - ## for each unique homologous sequence. - if sequence: - - cmd = 'SELECT CONCAT("Phy", p.protid, "_", s.code) AS protid, seq FROM ' - cmd += 'protein AS p, species AS s, unique_protein AS u WHERE(p.protid IN' - cmd += ' (%s) AND p.taxid = s.taxid AND p.protid = u.protid)' % (protids) - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - data["seq"][row["protid"]]["seq"] = row["seq"] - - ## Retrieve the external ids for all the unique sequences in the tree - for protid, external in self.get_external_ids(ids).iteritems(): - data["seq"][protid].setdefault("external", {}) - data["seq"][protid]["external"] = external - - for protid, external in self.get_go_ids(ids).iteritems(): - data["seq"][protid].setdefault("external", {}) - data["seq"][protid]["external"].update(external) - - for protid, external in self.get_old_phylomedb_ids(ids).iteritems(): - data["seq"][protid].setdefault("external", {}) - data["seq"][protid]["external"].update(external) - - for protid, external in self.get_prot_gene_names(ids).iteritems(): - data["seq"][protid].setdefault("external", {}) - data["seq"][protid]["external"].update(external) - - ## The sequence name is as well stored to considerer how many times a given - ## sequence has been used. That is related to copy number variation cases - data.setdefault("leaf_names", leaves) - - ## Recover additional information for all leaves in the tree such as - ## gene/protein names or copy number - cmd = 'SELECT CONCAT("Phy", p.protid, "_", s.code) AS protid, copy, ' - cmd += 'prot_name, gene_name FROM protein AS p, species AS s, ' - cmd += '%s AS ph, %s AS pc WHERE (p.' % (self._phylomes, self._phy_content) - cmd += 'protid IN (%s) AND p.taxid = s.taxid AND p.taxid = pc.' % (protids) - cmd += 'taxid AND pc.phylome_id = %s AND ph.phylome_id = pc.' % (phylome_id) - cmd += 'phylome_id AND pc.version = p.version)' - - ## Get specificy information for each tree's leaf, the information will be - ## the same that for an unique sequence if the copy_var_support is not - ## set up in advance. The copy_var_support points when there are more than - ## one copy for at least one unique sequence in the tree and specific - ## information for each copy can be put it in the tree - if self.__execute__(cmd): - data.setdefault("leaves", {}) - - for row in self._SQL.fetchall(): - code = row["protid"] - - if data["seq"][row["protid"]]["copy"] > 1 and copy_var_support: - #code += ("_%d") % (row["copy"]) - pass - if not copy_var_support and row["copy"] > 1 or not code in leaves: - continue - - data["leaves"].setdefault(code, {}) - data["leaves"][code]["gene"] = row["gene_name"] - data["leaves"][code]["protein"] = row["prot_name"] - data["leaves"][code]["copy_version"] = row["copy"] - - return data - - def get_all_isoforms(self, id): - """ Returns all the isoforms registered for the input phylomeDB ID - """ - - ## Check if the protein id is well-constructed - if not self.__check_input_parameter__(single_id = id): - raise NameError("get_all_isoforms: Check your input data") - protid = self.__parser_ids__(id) - - ## Look for different isoforms asocciated to the input phylomeDB ID - cmd = 'SELECT CONCAT("Phy", isoform) AS i, CONCAT("Phy", longest) AS l ' - cmd += 'FROM isoform WHERE(isoform = %s OR longest = %s)' % (protid, protid) - - ## Try to get the isoform for the input ID. Otherwise, return an empty dict - if not self.__execute__(cmd): - return {} - ids = self.__parser_ids__([r[k] for r in self._SQL.fetchall() for k in r]) - - ## Recover some details about every isoform - cmd = 'SELECT CONCAT("Phy", p.protid, "_", code) AS protid, LENGTH(seq) ' - cmd += 'AS ln FROM protein AS p, species AS s, unique_protein AS u WHERE p.' - cmd += 'protid IN (%s) AND p.protid = u.protid AND p.taxid = s.taxid' %(ids) - - isoforms = {} - ## Store the information about each isoform if it is not the input one - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - isoforms[row["protid"]] = int(row["ln"]) - return isoforms - - def get_longest_isoform(self, id): - """ Returns the longest isoform for a given phylomeDB ID - """ - - # Check if the ID is well-constructed - if not self.__check_input_parameter__(single_id = id): - raise NameError("get_longest_isoform fuction: Check your input data") - protid = self.__parser_ids__(id) - - # Look for different isoforms asocciated to the same gene/protein - cmd = 'SELECT DISTINCT CONCAT("Phy", p.protid, "_", s.code) as protid, s.' - cmd += 'code, p.version FROM protein AS p, species AS s, isoform AS i ' - cmd += 'WHERE (i.longest = p.protid AND i.version = p.version AND p.taxid ' - cmd += '= s.taxid AND i.isoform = %s)' % (protid) - - isoforms = {} - # Return the longest available isoforms for each proteome where the ID is - # already register - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - isoforms.setdefault(row["code"], {}).setdefault(int(row["version"]), []) - isoforms[row["code"]][int(row["version"])].append(row["protid"]) - return isoforms - - def get_id_by_external(self, external): - """ Returns the protein id associated to a given external id - """ - - if not self.__check_input_parameter__(code = external): - raise NameError("get_id_by_external: Check your input data") - - ## Look at external_db table for any available conversion - cmd = 'SELECT DISTINCT CONCAT("Phy", p.protid, "_", code) AS protid FROM ' - cmd += 'external_id AS e, protein AS p, species AS s WHERE (e.external_id ' - cmd += '= "%s" AND e.protid = p.protid AND p.taxid = s.taxid)' % (external) - - ids = {} - ## Recover any available translation - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - for sp, proteome in self.get_longest_isoform(row["protid"]).iteritems(): - for id, proteins in proteome.iteritems(): - ids.setdefault(sp, {}).setdefault(id, []) - ids[sp][id] += proteins - - ## Extend the information looking at protein and gene names in the protein - ## table - cmd = 'SELECT DISTINCT CONCAT("Phy", p.protid, "_", code) AS protid FROM ' - cmd += 'protein AS p, species AS s WHERE ((prot_name = "%s" OR' % (external) - cmd += ' gene_name = "%s") AND p.taxid = s.taxid)' % (external) - - ## Recover any available translation - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - for sp, proteome in self.get_longest_isoform(row["protid"]).iteritems(): - for id, proteins in proteome.iteritems(): - ids.setdefault(sp, {}).setdefault(id, []) - ids[sp][id] += proteins - - for sp in ids: - for proteome in ids[sp]: - ids[sp][proteome] = list(set(ids[sp][proteome])) - - return ids - - def search_id(self, id): - """ Returns a list of the longest isoforms for each proteome where the ID is - already registered. The ID can be a current phylomeDB ID version, former - phylomeDB ID or an external ID. - """ - - # Check if the ID is well-constructed - if not self.__check_input_parameter__(string = id): - raise NameError("search_id: Check your input data") - query = id.strip() - - # To avoid weird queries which creates slow or invalid MYSQL queries - QUERY_GEN_REGEXP_FILTER = "^[\w\d\-_,;:.|#@\/\\\()'<>!]+$" - QUERY_OLD_REGEXP_FILTER = "^\w{3}\d{1,}$" - QUERY_INT_REGEXP_FILTER = "^[Pp][Hh][Yy]\w{7}(_\w{2,7})?$" - - phylomeDB_matches = {} - # First, check if it is a current phylomeDB ID - if re.match(QUERY_INT_REGEXP_FILTER, query): - phylomeDB_matches = self.get_longest_isoform(query) - - # Second, check if it is a former phylomeDB ID - if phylomeDB_matches == {} and re.match(QUERY_OLD_REGEXP_FILTER, query): - currentID = self.get_new_phylomedb_id(query) - if currentID: - phylomeDB_matches = self.get_longest_isoform(currentID) - - # Third, check if the query can be mapped using other sources - if phylomeDB_matches == {} and re.match(QUERY_GEN_REGEXP_FILTER, query): - phylomeDB_matches = self.get_id_by_external(query) - - return phylomeDB_matches - - def get_id_translations(self, id): - """ Returns all the registered translations of a given phylomeDB ID - """ - - # Check if the ID is well-constructed - if not self.__check_input_parameter__(single_id = id): - raise NameError("get_id_translations: Check your input data") - - conversion = {} - ## Look at different external IDs sources and retrieve the available info - info = self.get_external_ids(id) - if info: - conversion.update(info[info.keys()[0]]) - - info = self.get_go_ids(id) - if info: - conversion.update(info[info.keys()[0]]) - - info = self.get_old_phylomedb_ids(id) - if info: - conversion.update(info[info.keys()[0]]) - - info = self.get_prot_gene_names(id) - if info: - conversion.update(info[info.keys()[0]]) - - return conversion - - def get_translations_for_proteome(self, taxid, version): - cmd = 'SELECT protid, prot_name, gene_name FROM protein WHERE taxid=%d AND version=%d' %\ - (taxid, version) - - if self.__execute__(cmd): - return [(r["protid"], r["prot_name"], r["gene_name"]) for r in self._SQL.fetchall()] - else: - return [] - - - def get_collateral_seeds(self, protid): - """ Return the trees where the protid is presented as part of the homolog - sequences to the seed protein - """ - - # Check if the input phylomeDB ID is well-constructed - if not self.__check_input_parameter__(list_id = protid): - raise NameError("get_collateral_seeds: Check your input data") - protid = self.__parser_ids__(protid) - - ## Recover the tree's seed protein and the phylome ID where the sequence is - ## among the homolog sequences - cmd = 'SELECT DISTINCT CONCAT("Phy", p.protid, "_", code) AS protid, sf.' - cmd += 'phylome_id AS phylome FROM seed_friend AS sf, species AS s, protein' - cmd += ' AS p, %s AS ph WHERE (friend_id IN (%s)' % (self._phylomes, protid) - cmd += ' AND sf.protid = p.protid AND p.taxid = s.taxid AND ph.phylome_id =' - cmd += ' sf.phylome_id)' - - ## Perform and return the query result - if self.__execute__(cmd): - return [(r["protid"], r["phylome"]) for r in self._SQL.fetchall()] - return [] - - def get_tree(self, id, phylome_id, method = None, best_tree = False): - """ Depending in the input parameters select either - .- a tree with the best evolutionary model in terms of LK (best_tree) - .- a tree reconstructed using a specific model (method) - .- all available model/trees for the tuple (phylomeDB ID, phylome ID) - """ - - # Check if the input parameters are well-constructed - if not self.__check_input_parameter__(single_id = id, str_number = phylome_id): - raise NameError("get_tree: Check your input data") - protid = self.__parser_ids__(id) - - if method and best_tree: - msg = "get_tree: Impossible to ask for the best model and ask at the " - msg += "same time for a specific evolutionary model" - raise NameError(msg) - - # Depending in the input parameters select either a tree with the best - # evolutionary model in terms of LK, excluiding any possible NJ tree; a tree - # reconstructed using a specific model or all available model/trees for the - # input ID associated to the input phylome - cmd = 'SELECT newick AS tree, method, lk FROM %s WHERE ' % (self._trees) - cmd += '(protid = %s AND phylome_id = %s)' % (protid, phylome_id) - - if best_tree: - cmd = cmd[:-1] + ' AND method != "NJ") ORDER BY lk DESC LIMIT 1' - elif method: - cmd = cmd[:-1] + ' AND method = "%s")' % (method) - - trees = {} - ## Execute the MySQL query and then format the query result - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - trees.setdefault(row["method"], {})["lk"] = row["lk"] - trees.setdefault(row["method"], {})["tree"] = PhyloTree(row["tree"], sp_naming_function=extract_species_name) - return trees - - def get_best_tree(self, id, phylome_id): - """ return a tree for input id in the given phylome for the best fitting - evolutionary model in terms of LK - """ - - # Check if the input parameters are well-constructed - if not self.__check_input_parameter__(single_id = id, str_number = phylome_id): - raise NameError("get_tree: Check your input data") - - protid = self.__parser_ids__(id) - # Select a tree with the best evolutionary model in terms of LK, excluiding - # any possible NJ tree; a tree - cmd = 'SELECT newick AS tree, method, lk FROM %s WHERE ' % (self._trees) - cmd += '(protid = %s AND phylome_id = %s AND method' % (protid, phylome_id) - cmd += ' != "NJ") ORDER BY lk DESC LIMIT 1' - - tree = {} - ## Execute the MySQL query and then format the query result - if self.__execute__(cmd): - tree = self._SQL.fetchone() - tree["tree"] = PhyloTree(tree["tree"], sp_naming_function=extract_species_name) - - return tree - - def get_algs(self, id, phylome_id, raw_alg = True, clean_alg = True): - """ Return the either the clean, the raw or both alignments for the input - phylomeDB ID in the input phylome - """ - - # Check if the input parameters are well-constructed - if not self.__check_input_parameter__(single_id = id, str_number = phylome_id): - raise NameError("get_algs: Check your input data") - protid = self.__parser_ids__(id) - - ## Check whether the function has to return, at least, one alignment - if not raw_alg and not clean_alg: - return {} - - ## Depending on the input parameters, construct the MySQL query asking for - ## either clean, raw or both alignments - cmd = "raw_alg, clean_alg" if raw_alg and clean_alg else "raw_alg" \ - if raw_alg else "clean_alg" - - cmd = 'SELECT %s, seqnumber FROM %s WHERE ' % (cmd, self._algs) - cmd += '(phylome_id = %s AND protid = %s)' % (phylome_id, protid) - - if self.__execute__(cmd): - return self._SQL.fetchone() - return {} - - def get_raw_alg(self, id, phylome_id): - """ Return the raw alignment for the input phylomeDB ID in the given phylome - """ - - # Check if the input parameters are well-constructed - if not self.__check_input_parameter__(single_id = id,str_number=phylome_id): - raise NameError("get_raw_alg: Check your input data") - - cmd = 'SELECT raw_alg FROM %s WHERE (phylome_id = ' % (self._algs) - cmd += '%s AND protid = %s)' % (phylome_id, self.__parser_ids__(id)) - - if self.__execute__(cmd): - return self._SQL.fetchone()["raw_alg"] - return "" - - def get_clean_alg(self, id, phylome_id): - """ Return the raw alignment for the input phylomeDB ID in the given phylome - """ - - # Check if the input parameters are well-constructed - if not self.__check_input_parameter__(single_id = id,str_number=phylome_id): - raise NameError("get_raw_alg: Check your input data") - - cmd = 'SELECT clean_alg FROM %s WHERE (phylome_id = ' % (self._algs) - cmd += '%s AND protid = %s)' % (phylome_id, self.__parser_ids__(id)) - - if self.__execute__(cmd): - return self._SQL.fetchone()["clean_alg"] - return "" - - def get_seq_info_in_tree(self, id, phylome_id, method = None): - """ Return all the available information for each sequence from tree/s - asociated to a tuple (protein, phylome) identifiers. - """ - - # Check if the input parameters are well-constructed - if not self.__check_input_parameter__(single_id = id, string = method, \ - str_number = phylome_id): - raise NameError("get_seq_info_in_tree: Check your input data") - - ## Depending on the input parameter, retrieve the best tree associated to - ## the phylomeDB ID in the given phylomeDB or retrieve the tree generated - ## under the model indicated in the input parameter. Moreover, all the - ## available information in the database for tree leaves - if method: - return self.get_info_homologous_seqs(id, phylome_id, tree = True, \ - tree_method = method) - else: - return self.get_info_homologous_seqs(id, phylome_id, tree = True) - - def get_seq_info_msf(self, id, phylome_id): - """ Return all available information for the homologous sequences to the - input phylomeDB ID in the input phylome using the best tree to compute - the set of homologous sequences - """ - - ## Check the input parameters - if not self.__check_input_parameter__(single_id = id, str_number = phylome_id): - raise NameError("get_seq_info_msf: Check your input parameters") - - ## The best tree is used to compute the homologous sequences for the input - ## phylomeDB ID and phylome ID. The tree is used to compute possible cases - ## of copy number variation where more than one copy for a given sequence - ## might be present in the set of homologous - return self.get_info_homologous_seqs(id, phylome_id, sequence = True) - - def get_seqid_info(self, id): - """ Returns available information about a given protid - """ - - # Check if the protein id is well-constructed - if not self.__check_input_parameter__(single_id = id): - raise NameError("Wrong id [%s]" %id) - protid = self.__parser_ids__(id) - - ## Join and retrieve all the information available in the database for - ## the sequence - cmd = 'SELECT DISTINCT CONCAT("Phy", p.protid, "_", s.code) AS protid, s.' - cmd += 'code AS species_code, s.name AS species_name, p.taxid, u.seq FROM ' - cmd += 'protein AS p, unique_protein AS u, species AS s WHERE (p.protid = ' - cmd += '%s AND p.protid = u.protid AND p.taxid = s.taxid)' % (protid) - - if not self.__execute__(cmd): - return {} - data = self._SQL.fetchone() - - ## Retrieve the information specific for each proteome version as well as - ## for the different copies inside each proteome - cmd = 'SELECT version, copy, prot_name, gene_name, comments FROM protein ' - cmd += 'WHERE protid = %s' % (protid) - - if not self.__execute__(cmd): - return {} - - for row in self._SQL.fetchall(): - proteome = ("%s.%s") % (data["species_code"], row["version"]) - data.setdefault("proteomes", set()).add(proteome) - - data.setdefault("copy", {}).setdefault(proteome, 0) - data["copy"][proteome] = row["copy"] if data["copy"][proteome] < \ - row["copy"] else data["copy"][proteome] - - if row["prot_name"]: - data.setdefault("protein", {}).setdefault(proteome, set()).\ - add(row["prot_name"]) - - if row["gene_name"]: - data.setdefault("gene", {}).setdefault(proteome, set()).\ - add(row["gene_name"]) - - if row["comments"]: - data.setdefault("comments", {}).setdefault(proteome, set()).\ - add(row["comments"]) - - ## Recover all the isoforms associated to the input phylomeDB ID - data["isoforms"] = self.get_all_isoforms(data["protid"]) - - ## Look at different external IDs sources and retrieve the available info - info = self.get_external_ids(id) - data["external"] = info[info.keys()[0]] if info else {} - - info = self.get_go_ids(id) - if info: - data["external"].update(info[info.keys()[0]]) - - info = self.get_old_phylomedb_ids(id) - if info: - data["external"].update(info[info.keys()[0]]) - - info = self.get_prot_gene_names(id) - if info: - data["external"].update(info[info.keys()[0]]) - - return data - - def get_available_trees_by_phylome(self, id, collateral = True): - """ Returns information about which methods have been used to reconstruct - every tree for a given phylomeDB ID grouped by phylome - """ - - # Check if the input parameters are well-constructed - if not self.__check_input_parameter__(list_id = id, boolean = collateral): - raise NameError("Check your input data") - protids = self.__parser_ids__(id) - - ## Retrieve which models were used to reconstructed the trees in each - ## phylome where the input phylomeDB ID was used as a seed - cmd = 'SELECT DISTINCT phylome_id, method, CONCAT("Phy", p.protid, "_", s.' - cmd += 'code) AS protid FROM protein AS p, species AS s, %s' % (self._trees) - cmd += ' AS t WHERE (p.protid IN (%s) AND p.protid = t.protid ' % (protids) - cmd += 'AND p.taxid = s.taxid)' - - if not self.__execute__(cmd) and not collateral: - return {} - - t = {} - ## Create a temporary structure to process the data retrieved - for r in self._SQL.fetchall(): - t.setdefault(int(r["phylome_id"]), {}) - t[int(r["phylome_id"])].setdefault(r["protid"], set()).add(r["method"]) - - trees = {} - ## Create the definitive data structure where the IDs with the methods used - ## to reconstructed each tree are grouped by phylome - for phylome in t: - trees.setdefault(phylome, []) - for protid in t[phylome]: - trees[phylome].append([True, protid, [m for m in t[phylome][protid]]]) - - ## Retrieve the trees where the input phylomeDB ID has been used as part of - ## the set of homologous sequences to make the tree - if collateral: - for seed, phylome in self.get_collateral_seeds(id): - cmd = 'SELECT method FROM %s WHERE protid = ' % (self._trees) - cmd += '%s AND phylome_id = %s' % (self.__parser_ids__(seed), phylome) - if self.__execute__(cmd): - trees.setdefault(int(phylome), []).append([False, seed, [r["method"] \ - for r in self._SQL.fetchall()]]) - - return trees - - def count_trees(self, phylome_id): - """ Retuns the frequency of each evolutionary method in the input phylome - """ - # Check if the phylome id is well-constructed - if not self.__check_input_parameter__(str_number = phylome_id): - raise NameError("count_trees: Check your input data") - - cmd = 'SELECT method, count(*) AS freq FROM %s WHERE ' % (self._trees) - cmd += '(phylome_id = %s) GROUP BY method' % (phylome_id) - - if self.__execute__(cmd): - return self.__fomat_MySQL_to_dict__("method", self._SQL.fetchall()) - return {} - - def count_algs(self, phylome_id): - """ Returns how many alignments are for a given phylome - """ - - # Check if the phylomedb id code is well-constructed - if not self.__check_input_parameter__(str_number = phylome_id): - raise NameError("count_algs: Check your input data") - - cmd = 'SELECT count(*) AS freq FROM %s ' % (self._algs) - cmd += 'WHERE phylome_id = %s' % (phylome_id) - - if self.__execute__(cmd): - return int(self._SQL.fetchone()["freq"]) - return 0 - - def get_phylome_trees(self, phylome_id): - """ Returns all trees available for a given phylome - """ - - # Check if the phylome id code is well-constructed - if not self.__check_input_parameter__(str_number = phylome_id): - raise NameError("get_phylome_trees: Check your input data") - - ## Get all available trees for a given phylome id - cmd = 'SELECT CONCAT("Phy", protid, "_", code) AS protid, method, lk, ' - cmd += 'newick FROM %s AS t, %s AS ph, ' % (self._trees, self._phylomes) - cmd += 'species AS s WHERE (ph.phylome_id = %s AND ph.' % (phylome_id) - cmd += 'phylome_id = t.phylome_id AND ph.seed_taxid = s.taxid)' - - trees = {} - ## For each phylomeDB ID used as a seed, return the different evolutionary - ## model evaluated during the phylogenetic reconstruction as well as the - ## phylogenetic tree (an ETE object) and its likelihood - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - trees.setdefault(row["protid"], {}).setdefault(row["method"], \ - [row["lk"], PhyloTree(row["newick"], sp_naming_function=extract_species_name)]) - return trees - - def get_phylome_algs(self, phylome_id): - """ Returns all alignments available for a given phylome - """ - - # Check if the phylome id code is well-constructed - if not self.__check_input_parameter__(str_number = phylome_id): - raise NameError("get_phylome_tree: Check your input data") - - ## Retrieve all the available alignments for the input phylome - cmd = 'SELECT CONCAT("Phy", protid, "_", code) AS protid, raw_alg, clean_' - cmd += 'alg FROM %s AS a, %s AS ph, species ' % (self._algs, self._phylomes) - cmd += 'AS s WHERE (ph.phylome_id = %s AND ph.phylome_id = ' % (phylome_id) - cmd += 'a.phylome_id AND ph.seed_taxid = s.taxid)' - - algs = {} - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - algs.setdefault(row["protid"], {})["raw_alg"] = row["raw_alg"] - algs.setdefault(row["protid"], {})["clean_alg"] = row["clean_alg"] - return algs - - def get_species(self): - """ Returns all current registered species in the database - """ - - if self.__execute__('SELECT taxid, code, name FROM species'): - return self.__fomat_MySQL_to_dict__("code", self._SQL.fetchall()) - return {} - - def get_species_info(self, taxid = None, code = None): - """ Returns all information on a given species/code - """ - - # Check if the input parameters is well-constructed - if not self.__check_input_parameter__(number = taxid, string = code): - raise NameError("Check your input data") - - if not taxid and not code: - return {} - - ## Depending on the input parameters, the search in the database is perfomed - ## using either species taxid, or species code or both of them. - cmd = 'SELECT taxid, code, name FROM species AS s WHERE (' - cmd += 'taxid = %s%s' % (taxid, '' if code else ')') if taxid else "" - cmd += '%s code = "%s")' % (" AND" if taxid else "", code) if code else "" - - ## Return the retrieved information - if self.__execute__(cmd): - return self._SQL.fetchone() - return {} - - def get_genomes(self): - """ Returns all current available genomes/proteomes - """ - - ## Complete information about each genome adding species information - cmd = 'SELECT CONCAT(code, ".",version) AS g, g.taxid, source, DATE(date),' - cmd += ' AS date,name FROM genome AS g, species AS s WHERE s.taxid =g.taxid' - - if self.__execute__(cmd): - return self.__fomat_MySQL_to_dict__("g", self._SQL.fetchall()) - return {} - - def get_genome_info(self, genome): - """ Returns all available information about a registered genome/proteome - """ - - # Check if the input parameter is well-constructed - if not self.__check_input_parameter__(string = genome): - raise NameError("get_genome_info: Check your input data") - - if genome.count(".") != 1: - raise NameError("get_genome_info: Expected input 'SpeciesCode.version'") - - code, version = genome.split(".") - ## If the genome is well-defined, ask for its associated information - cmd = 'SELECT CONCAT(code, ".", version) AS genome_id, g.taxid, s.name AS ' - cmd += 'species, version, DATE(date) AS date, source, comments FROM species' - cmd += ' AS s, genome AS g WHERE(s.taxid = g.taxid AND code = "%s"' % (code) - cmd += ' AND version = %s)' % (version) - - ## Return the available information in a dictionary defined for that - if self.__execute__(cmd): - return self._SQL.fetchone() - return {} - - def get_genome_ids(self, taxid, version, filter_isoforms = True): - """ Returns the phylomeDB IDs for a given genome in the database filtering - out, or not, the different isoforms for each ID - """ - - ## Check if the input parameters are well-constructed - if not self.__check_input_parameter__(str_number = taxid): - raise NameError("get_genome_ids: Check your input data") - if not self.__check_input_parameter__(str_number = version): - raise NameError("get_genome_ids: Check your input data") - if not self.__check_input_parameter__(boolean = filter_isoforms): - raise NameError("get_genome_ids: Check your input data") - - ## Depending on if the different isoforms have to be filter out or not, the - ## query to retrieve the phylomeDB IDs is different - if filter_isoforms: - cmd = 'SELECT DISTINCT CONCAT("Phy", i.longest, "_", s.code) AS protid ' - cmd += 'FROM protein AS p, isoform AS i, species AS s WHERE p.taxid = ' - cmd += '%s AND p.version = %s AND p.protid = i.isoform' % (taxid, version) - cmd += ' AND p.version = i.version AND p.taxid = s.taxid' - else: - cmd = 'SELECT DISTINCT CONCAT("Phy", protid, "_", code) AS protid FROM ' - cmd += 'protein AS p, species AS s WHERE p.taxid = %s AND p.' % (taxid) - cmd += 'version = %s AND p.taxid = s.taxid' % (version) - - if not self.__execute__(cmd): - return [] - - ## Retrieve all the information available for the selected phylomeDB IDs - return [row["protid"] for row in self._SQL.fetchall()] - - def get_genomes_by_species(self, taxid): - """ Return all the proteomes/genomes registered for the input taxaid code - """ - - # Check if the input parameter is well-constructed - if not self.__check_input_parameter__(str_number = taxid): - raise NameError("Check your input data") - - # Look for the different versions of the input taxid - cmd = 'SELECT CONCAT(code, ".", version) AS genome FROM species AS s, ' - cmd += 'genome AS g WHERE s.taxid = %s AND s.taxid = g.taxid' % (taxid) - - genomes = {} - if self.__execute__(cmd): - genomes[taxid] = [row["genome"] for row in self._SQL.fetchall()] - return genomes - - def get_phylomes(self): - """ Returns all current available phylomes - """ - - ## Recover all the phylomes stored in the database - cmd = 'SELECT phylome_id, seed_taxid, s.name AS seed_species, CONCAT(code,' - cmd += ' ".", seed_version) AS seed_proteome, DATE(ts) AS date, comments, ' - cmd += 'ph.name FROM species AS s, %s AS ph WHERE seed_' % (self._phylomes) - cmd += 'taxid = s.taxid' - - ## Generate a dictionary with all phylomes - if self.__execute__(cmd): - return self.__fomat_MySQL_to_dict__("phylome_id", self._SQL.fetchall()) - return {} - - def get_phylome_info(self, phylome_id): - """ Returns available information on a given phylome - """ - - # Check if the phylome id code is well-constructed - if not self.__check_input_parameter__(str_number = phylome_id): - raise NameError("get_phylome_info: Check your input data") - - ## Get all available data for the input phylome - cmd = 'SELECT phylome_id AS id, seed_taxid, s.name AS seed_species, CONCAT' - cmd += '(code, ".", seed_version) AS seed_proteome, DATE(ts) AS date, ph.' - cmd += 'name, comments FROM species AS s, %s AS ph WHERE' % (self._phylomes) - cmd += '(ph.phylome_id = %s AND ph.seed_taxid = s.taxid)' % (phylome_id) - - if self.__execute__(cmd): - return self._SQL.fetchone() - return {} - - def get_phylome_seed_ids(self, phylome_id, filter_isoforms = True): - """ Returns the seed phylomeDB IDs for a given phylome being possible to - filter out the longest isoforms - """ - - ## Check if the input parameters are well-constructed - if not self.__check_input_parameter__(str_number = phylome_id): - raise NameError("get_seed_ids: Check your input data (1)") - if not self.__check_input_parameter__(boolean = filter_isoforms): - raise NameError("get_seed_ids: Check your input data (2)") - - ## Get the seed species and version for the input phylome - cmd = 'SELECT seed_taxid, seed_version FROM %s ' % (self._phylomes) - cmd += 'WHERE phylome_id = %s' % (phylome_id) - - ## Retrieve the IDs - if self.__execute__(cmd): - row = self._SQL.fetchone() - ## Return the IDs as well as the taxid and proteome version used to - ## reconstruct the phylome. It might be useful for others functions - return self.get_genome_ids(row["seed_taxid"], row["seed_version"], \ - filter_isoforms), row["seed_taxid"], row["seed_version"] - return [] - - def get_proteomes_in_phylome(self, phylome_id): - """ Returns a list of proteomes associated to a given phylome_id - """ - - # Check if the phylome id code is well-constructed - if not self.__check_input_parameter__(str_number = phylome_id): - raise NameError("get_proteomes_in_phylome: Check your input data") - - ## Retrieve the proteomes associated to the phylome - cmd = 'SELECT s.taxid, CONCAT(code, ".", pc.version) AS proteome, s.name,' - cmd += ' source, date, pc.version FROM species AS s, %s ' % (self._phylomes) - cmd += 'AS ph, %s AS pc, genome AS g WHERE ph.phylome' % (self._phy_content) - cmd += '_id = %s AND ph.phylome_id = pc.phylome_id AND pc.' % (phylome_id) - cmd += 'taxid = s.taxid AND pc.taxid = g.taxid AND pc.version = g.version' - - proteomes = {} - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - proteomes.setdefault("proteomes", {}).setdefault(row["proteome"], row) - - cmd = 'SELECT CONCAT(code, ".", ph.seed_version) AS proteome FROM ' - cmd += 'species AS s, %s AS ph WHERE (ph.phylome_id = ' % (self._phylomes) - cmd += '%s AND ph.seed_taxid = s.taxid)' % (phylome_id) - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - proteomes["seed"] = row["proteome"] - - return proteomes - - def get_species_in_phylome(self, phylome_id): - """ Returns a list of proteomes associated to a given phylome_id - """ - ## Retrieve taxids associated to a phylome - cmd = 'SELECT taxid from %s WHERE phylome_id="%s"' % \ - (self._phy_content, phylome_id) - if self.__execute__(cmd): - return [values["taxid"] for values in self._SQL.fetchall()] - else: - return [] - - def get_phylomes_for_seed_ids(self, ids): - """ Given a list of phylomeDB IDs, return in which phylomes these IDs have - been used as a seed - """ - - ## Check if the input parameter is well-constructed - if not self.__check_input_parameter__(list_id = ids): - raise NameError("get_phylomes_for_seed_ids: Check your input data") - - ## Get all phylomes where the input phylome IDs have been used as a seed - cmd = 'SELECT CONCAT("Phy", t.protid, "_", code) AS protid, t.phylome_id,' - cmd += ' ph.name FROM %s AS t, %s AS ph, ' % (self._trees, self._phylomes) - cmd += 'species AS s WHERE (t.protid IN (%s) ' % (self.__parser_ids__(ids)) - cmd += 'AND t.phylome_id = ph.phylome_id AND ph.seed_taxid = s.taxid) ' - cmd += 'GROUP BY t.protid, ph.phylome_id' - - phylomes = {} - if self.__execute__(cmd): - for r in self._SQL.fetchall(): - phylomes.setdefault(r["protid"], []).append((r["phylome_id"],r["name"])) - return phylomes - - def get_seqs_in_genome(self, taxid, version, filter_isoforms = True): - """ Returns all sequences of a given proteome, filtering the - """ - - ## Check if the input parameters are well-constructed - if not self.__check_input_parameter__(str_number = taxid): - raise NameError("get_seqs_in_genome: Check your input data") - if not self.__check_input_parameter__(str_number = version): - raise NameError("get_seqs_in_genome: Check your input data") - if not self.__check_input_parameter__(boolean = filter_isoforms): - raise NameError("get_seqs_in_genome: Check your input data") - - ## Retrieve the phylomeDB IDs for the input genome - ids = self.get_genome_ids(taxid, version, filter_isoforms) - - ## Get all the information - cmd = 'SELECT CONCAT("Phy", p.protid, "_",code) AS protid, copy, prot_name,' - cmd += ' gene_name, seq FROM protein AS p, species AS s, unique_protein AS ' - cmd += 'u WHERE p.protid IN (%s) AND p.version' % (self.__parser_ids__(ids)) - cmd += ' = %s AND p.taxid = s.taxid AND p.protid = u.protid' % (version) - - sequences = {} - ## Store the data into the appropiate data structure having in mind the - ## copy number variation effect. - if self.__execute__(cmd): - for row in self._SQL.fetchall(): - - if row["copy"] > 1 and row["protid"] in sequences: - sequences[("%s_1") % (row["protid"])] = sequences[row["protid"]] - del sequences[row["protid"]] - if row["copy"] > 1: - row["protid"] += ("_%d") % (row["copy"]) - - sequences[row["protid"]] = row - del sequences[row["protid"]]["protid"] - - return sequences - - def get_phylome_seed_ids_info(self, phylome_id, start = 0, offset = None, \ - filter_isoforms = False): - """ - """ - - ## Check if the input parameters are well-constructed - if not self.__check_input_parameter__(str_number = phylome_id): - raise NameError("get_phylome_seed_ids_info: Check your input data (1)") - if not self.__check_input_parameter__(str_number = start, number = offset): - raise NameError("get_phylome_seed_ids_info: Check your input data (2)") - - ## Determine how many phylomeDB IDs have been used as a seed in the input - ## phylome - ids, taxid, version = self.get_phylome_seed_ids(phylome_id, filter_isoforms) - protids = self.__parser_ids__(ids) - - ## Retrieve the phylomeDB IDs belonging to the input phylome as well the - ## number of trees for each ID in that phylome - cmd = 'SELECT CONCAT("Phy", p.protid, "_", s.code) AS protid, COUNT(' - cmd += 'DISTINCT method) AS trees FROM (protein AS p, species AS s, ' - cmd += '%s AS ph) LEFT JOIN (%s AS t) ON ' % (self._phylomes, self._trees) - cmd += '(ph.phylome_id = t.phylome_id AND p.protid = t.protid) WHERE (ph.' - cmd += 'phylome_id = %s AND ph.seed_taxid = p.taxid AND ph.' % (phylome_id) - cmd += 'seed_version = p.version AND ph.seed_taxid = s.taxid AND p.protid ' - cmd += 'IN (%s)) GROUP BY p.protid ORDER BY trees DESC, protid ' % (protids) - cmd += 'LIMIT %d,%d' % (start, offset) if offset else '' - - if not self.__execute__(cmd): - return {} - seqs = self.__fomat_MySQL_to_dict__("protid", self._SQL.fetchall()) - - protids = self.__parser_ids__(seqs.keys()) - cmd = 'SELECT CONCAT("Phy", p.protid, "_", s.code) AS protid, raw_alg IS ' - cmd += 'NOT NULL AS r, clean_alg IS NOT NULL AS c FROM (protein AS p, speci' - cmd += 'es AS s) LEFT JOIN (%s AS a) ON (p.protid = a.protid' % (self._algs) - cmd += ') WHERE (p.protid IN (%s) AND p.version = %s ' % (protids, version) - cmd += 'AND p.taxid = s.taxid AND a.phylome_id = %s)' % (phylome_id) - - if not self.__execute__(cmd): - return {} - - for row in self._SQL.fetchall(): - seqs[row["protid"]]["algs"] = 2 if row["r"] and row["c"] else 1 \ - if row["c"] or row["r"] else 0 - - cmd = 'SELECT CONCAT("Phy", p.protid, "_", s.code) AS protid, p.comments, ' - cmd += 'gene_name, prot_name, copy, length(seq) AS l FROM protein AS p, uni' - cmd += 'que_protein AS u, species AS s, %s AS ph WHERE ' % (self._phylomes) - cmd += '(ph.phylome_id = %s AND p.protid IN (%s) ' % (phylome_id, protids) - cmd += 'AND ph.seed_version = p.version AND ph.seed_taxid = s.taxid)' - - if not self.__execute__(cmd): - return {} - - for row in self._SQL.fetchall(): - seqs[row["protid"]]["seq_length"] = row["l"] - - seqs[row["protid"]].setdefault("copy", 0) - if row["copy"] > seqs[row["protid"]]["copy"]: - seqs[row["protid"]]["copy"] = row["copy"] - - return seqs, len(ids) diff --git a/ete2/phylomedb/phylomeDB3.pyc b/ete2/phylomedb/phylomeDB3.pyc deleted file mode 100644 index 349d716..0000000 Binary files a/ete2/phylomedb/phylomeDB3.pyc and /dev/null differ diff --git a/ete2/phyloxml/__init__.py b/ete2/phyloxml/__init__.py deleted file mode 100644 index 9e62201..0000000 --- a/ete2/phyloxml/__init__.py +++ /dev/null @@ -1,69 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -from sys import stdout -import _phyloxml as main -from _phyloxml import * -from _phyloxml_tree import PhyloxmlTree - -_phyloxml.Phylogeny.subclass = PhyloxmlTree - -class Phyloxml(_phyloxml.Phyloxml): - def __repr__(self): - return "PhyloXML project <%s>" %hex(hash(self)) - - def __init__(self, *args, **kargs): - _phyloxml.Phyloxml.__init__(self, *args, **kargs) - - def build_from_file(self, fname): - doc = _phyloxml.parsexml_(fname) - rootNode = doc.getroot() - rootTag, rootClass = _phyloxml.get_root_tag(rootNode) - if rootClass is None: - rootTag = 'phyloxml' - rootClass = self.__class__ - self.build(rootNode) - - def export(self, outfile=stdout, level=0): - namespace = 'xmlns:phy="http://www.phyloxml.org/1.10/phyloxml.xsd"' - return super(Phyloxml, self).export(outfile=outfile, level=level, namespacedef_=namespace) - - -__all__ = _phyloxml.__all__ + ["Phyloxml", "PhyloxmlTree"] diff --git a/ete2/phyloxml/__init__.pyc b/ete2/phyloxml/__init__.pyc deleted file mode 100644 index 53d14fc..0000000 Binary files a/ete2/phyloxml/__init__.pyc and /dev/null differ diff --git a/ete2/phyloxml/_phyloxml.py b/ete2/phyloxml/_phyloxml.py deleted file mode 100644 index 9c89528..0000000 --- a/ete2/phyloxml/_phyloxml.py +++ /dev/null @@ -1,4072 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Generated Mon Jun 27 10:13:44 2011 by generateDS.py version 2.5b. -# - -import sys -import getopt -import re as re_ - -etree_ = None -Verbose_import_ = False -( XMLParser_import_none, XMLParser_import_lxml, - XMLParser_import_elementtree - ) = range(3) -XMLParser_import_library = None -try: - # lxml - from lxml import etree as etree_ - XMLParser_import_library = XMLParser_import_lxml - if Verbose_import_: - print("running with lxml.etree") -except ImportError: - try: - # cElementTree from Python 2.5+ - import xml.etree.cElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with cElementTree on Python 2.5+") - except ImportError: - try: - # ElementTree from Python 2.5+ - import xml.etree.ElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with ElementTree on Python 2.5+") - except ImportError: - try: - # normal cElementTree install - import cElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with cElementTree") - except ImportError: - try: - # normal ElementTree install - import elementtree.ElementTree as etree_ - XMLParser_import_library = XMLParser_import_elementtree - if Verbose_import_: - print("running with ElementTree") - except ImportError: - raise ImportError("Failed to import ElementTree from any known place") - -def parsexml_(*args, **kwargs): - if (XMLParser_import_library == XMLParser_import_lxml and - 'parser' not in kwargs): - # Use the lxml ElementTree compatible parser so that, e.g., - # we ignore comments. - kwargs['parser'] = etree_.ETCompatXMLParser() - doc = etree_.parse(*args, **kwargs) - return doc - -# -# User methods -# -# Calls to the methods in these classes are generated by generateDS.py. -# You can replace these methods by re-implementing the following class -# in a module named generatedssuper.py. - -try: - from generatedssuper import GeneratedsSuper -except ImportError, exp: - - class GeneratedsSuper(object): - def gds_format_string(self, input_data, input_name=''): - return input_data - def gds_validate_string(self, input_data, node, input_name=''): - return input_data - def gds_format_integer(self, input_data, input_name=''): - return '%d' % input_data - def gds_validate_integer(self, input_data, node, input_name=''): - return input_data - def gds_format_integer_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_integer_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - try: - fvalue = float(value) - except (TypeError, ValueError), exp: - raise_parse_error(node, 'Requires sequence of integers') - return input_data - def gds_format_float(self, input_data, input_name=''): - return '%f' % input_data - def gds_validate_float(self, input_data, node, input_name=''): - return input_data - def gds_format_float_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_float_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - try: - fvalue = float(value) - except (TypeError, ValueError), exp: - raise_parse_error(node, 'Requires sequence of floats') - return input_data - def gds_format_double(self, input_data, input_name=''): - return '%e' % input_data - def gds_validate_double(self, input_data, node, input_name=''): - return input_data - def gds_format_double_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_double_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - try: - fvalue = float(value) - except (TypeError, ValueError), exp: - raise_parse_error(node, 'Requires sequence of doubles') - return input_data - def gds_format_boolean(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_boolean(self, input_data, node, input_name=''): - return input_data - def gds_format_boolean_list(self, input_data, input_name=''): - return '%s' % input_data - def gds_validate_boolean_list(self, input_data, node, input_name=''): - values = input_data.split() - for value in values: - if value not in ('true', '1', 'false', '0', ): - raise_parse_error(node, 'Requires sequence of booleans ("true", "1", "false", "0")') - return input_data - def gds_str_lower(self, instring): - return instring.lower() - def get_path_(self, node): - path_list = [] - self.get_path_list_(node, path_list) - path_list.reverse() - path = '/'.join(path_list) - return path - Tag_strip_pattern_ = re_.compile(r'\{.*\}') - def get_path_list_(self, node, path_list): - if node is None: - return - tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag) - if tag: - path_list.append(tag) - self.get_path_list_(node.getparent(), path_list) - - -# -# If you have installed IPython you can uncomment and use the following. -# IPython is available from http://ipython.scipy.org/. -# - -## from IPython.Shell import IPShellEmbed -## args = '' -## ipshell = IPShellEmbed(args, -## banner = 'Dropping into IPython', -## exit_msg = 'Leaving Interpreter, back to program.') - -# Then use the following line where and when you want to drop into the -# IPython shell: -# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit') - -# -# Globals -# - -ExternalEncoding = 'utf-8' -Tag_pattern_ = re_.compile(r'({.*})?(.*)') -STRING_CLEANUP_PAT = re_.compile(r"[\n\r\s]+") - -# -# Support/utility functions. -# - -def showIndent(outfile, level): - for idx in range(level): - outfile.write(' ') - -def quote_xml(inStr): - if not inStr: - return '' - s1 = (isinstance(inStr, basestring) and inStr or - '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - return s1 - -def quote_attrib(inStr): - s1 = (isinstance(inStr, basestring) and inStr or - '%s' % inStr) - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('>', '>') - if '"' in s1: - if "'" in s1: - s1 = '"%s"' % s1.replace('"', """) - else: - s1 = "'%s'" % s1 - else: - s1 = '"%s"' % s1 - return s1 - -def quote_python(inStr): - s1 = inStr - if s1.find("'") == -1: - if s1.find('\n') == -1: - return "'%s'" % s1 - else: - return "'''%s'''" % s1 - else: - if s1.find('"') != -1: - s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: - return '"%s"' % s1 - else: - return '"""%s"""' % s1 - -def get_all_text_(node): - if node.text is not None: - text = node.text - else: - text = '' - for child in node: - if child.tail is not None: - text += child.tail - return text - -def find_attr_value_(attr_name, node): - attrs = node.attrib - # First try with no namespace. - value = attrs.get(attr_name) - if value is None: - # Now try the other possible namespaces. - namespaces = node.nsmap.itervalues() - for namespace in namespaces: - value = attrs.get('{%s}%s' % (namespace, attr_name, )) - if value is not None: - break - return value - - -class GDSParseError(Exception): - pass - -def raise_parse_error(node, msg): - if XMLParser_import_library == XMLParser_import_lxml: - msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, ) - else: - msg = '%s (element %s)' % (msg, node.tag, ) - raise GDSParseError(msg) - - -class MixedContainer: - # Constants for category: - CategoryNone = 0 - CategoryText = 1 - CategorySimple = 2 - CategoryComplex = 3 - # Constants for content_type: - TypeNone = 0 - TypeText = 1 - TypeString = 2 - TypeInteger = 3 - TypeFloat = 4 - TypeDecimal = 5 - TypeDouble = 6 - TypeBoolean = 7 - def __init__(self, category, content_type, name, value): - self.category = category - self.content_type = content_type - self.name = name - self.value = value - def getCategory(self): - return self.category - def getContenttype(self, content_type): - return self.content_type - def getValue(self): - return self.value - def getName(self): - return self.name - def export(self, outfile, level, name, namespace): - if self.category == MixedContainer.CategoryText: - # Prevent exporting empty content as empty lines. - if self.value.strip(): - outfile.write(self.value) - elif self.category == MixedContainer.CategorySimple: - self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex - self.value.export(outfile, level, namespace,name) - def exportSimple(self, outfile, level, name): - if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % (self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % (self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % (self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % (self.name, self.value, self.name)) - def exportLiteral(self, outfile, level, name): - if self.category == MixedContainer.CategoryText: - showIndent(outfile, level) - outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) - elif self.category == MixedContainer.CategorySimple: - showIndent(outfile, level) - outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) - else: # category == MixedContainer.CategoryComplex - showIndent(outfile, level) - outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % \ - (self.category, self.content_type, self.name,)) - self.value.exportLiteral(outfile, level + 1) - showIndent(outfile, level) - outfile.write(')\n') - - -class MemberSpec_(object): - def __init__(self, name='', data_type='', container=0): - self.name = name - self.data_type = data_type - self.container = container - def set_name(self, name): self.name = name - def get_name(self): return self.name - def set_data_type(self, data_type): self.data_type = data_type - def get_data_type_chain(self): return self.data_type - def get_data_type(self): - if isinstance(self.data_type, list): - if len(self.data_type) > 0: - return self.data_type[-1] - else: - return 'xs:string' - else: - return self.data_type - def set_container(self, container): self.container = container - def get_container(self): return self.container - -def _cast(typ, value): - if typ is None or value is None: - return value - return typ(value) - -# -# Data representation classes. -# - -class Phyloxml(GeneratedsSuper): - """'phyloxml' is the name of the root element. Phyloxml contains an - arbitrary number of 'phylogeny' elements (each representing one - phylogeny) possibly followed by elements from other namespaces.""" - subclass = None - superclass = None - def __init__(self, phylogeny=None, valueOf_=None): - if phylogeny is None: - self.phylogeny = [] - else: - self.phylogeny = phylogeny - def factory(*args_, **kwargs_): - if Phyloxml.subclass: - return Phyloxml.subclass(*args_, **kwargs_) - else: - return Phyloxml(*args_, **kwargs_) - factory = staticmethod(factory) - def get_phylogeny(self): return self.phylogeny - def set_phylogeny(self, phylogeny): self.phylogeny = phylogeny - def add_phylogeny(self, value): self.phylogeny.append(value) - def insert_phylogeny(self, index, value): self.phylogeny[index] = value - def export(self, outfile, level, namespace_='phy:', name_='Phyloxml', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Phyloxml') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Phyloxml'): - pass - def exportChildren(self, outfile, level, namespace_='phy:', name_='Phyloxml', fromsubclass_=False): - for phylogeny_ in self.phylogeny: - phylogeny_.export(outfile, level, namespace_, name_='phylogeny') - def hasContent_(self): - if ( - self.phylogeny - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Phyloxml'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - pass - def exportLiteralChildren(self, outfile, level, name_): - showIndent(outfile, level) - outfile.write('phylogeny=[\n') - level += 1 - for phylogeny_ in self.phylogeny: - showIndent(outfile, level) - outfile.write('model_.Phylogeny(\n') - phylogeny_.exportLiteral(outfile, level, name_='Phylogeny') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'phylogeny': - obj_ = Phylogeny.factory() - obj_.build(child_) - self.phylogeny.append(obj_) -# end class Phyloxml - - -class Phylogeny(GeneratedsSuper): - """Element Phylogeny is used to represent a phylogeny. The required - attribute 'rooted' is used to indicate whether the phylogeny is - rooted or not. The attribute 'rerootable' can be used to - indicate that the phylogeny is not allowed to be rooted - differently (i.e. because it is associated with root dependent - data, such as gene duplications). The attribute 'type' can be - used to indicate the type of phylogeny (i.e. 'gene tree'). It is - recommended to use the attribute 'branch_length_unit' if the - phylogeny has branch lengths. Element clade is used in a - recursive manner to describe the topology of a phylogenetic - tree.""" - subclass = None - superclass = None - def __init__(self, rerootable=None, branch_length_unit=None, type_=None, rooted=None, name=None, id=None, description=None, date=None, confidence=None, clade=None, clade_relation=None, sequence_relation=None, property=None, valueOf_=None): - self.rerootable = _cast(bool, rerootable) - self.branch_length_unit = _cast(None, branch_length_unit) - self.type_ = _cast(None, type_) - self.rooted = _cast(bool, rooted) - self.name = name - self.id = id - self.description = description - self.date = date - if confidence is None: - self.confidence = [] - else: - self.confidence = confidence - self.clade = clade - if clade_relation is None: - self.clade_relation = [] - else: - self.clade_relation = clade_relation - if sequence_relation is None: - self.sequence_relation = [] - else: - self.sequence_relation = sequence_relation - if property is None: - self.property = [] - else: - self.property = property - def factory(*args_, **kwargs_): - if Phylogeny.subclass: - return Phylogeny.subclass(*args_, **kwargs_) - else: - return Phylogeny(*args_, **kwargs_) - factory = staticmethod(factory) - def get_name(self): return self.name - def set_name(self, name): self.name = name - def get_id(self): return self.id - def set_id(self, id): self.id = id - def get_description(self): return self.description - def set_description(self, description): self.description = description - def get_date(self): return self.date - def set_date(self, date): self.date = date - def get_confidence(self): return self.confidence - def set_confidence(self, confidence): self.confidence = confidence - def add_confidence(self, value): self.confidence.append(value) - def insert_confidence(self, index, value): self.confidence[index] = value - def get_clade(self): return self.clade - def set_clade(self, clade): self.clade = clade - def get_clade_relation(self): return self.clade_relation - def set_clade_relation(self, clade_relation): self.clade_relation = clade_relation - def add_clade_relation(self, value): self.clade_relation.append(value) - def insert_clade_relation(self, index, value): self.clade_relation[index] = value - def get_sequence_relation(self): return self.sequence_relation - def set_sequence_relation(self, sequence_relation): self.sequence_relation = sequence_relation - def add_sequence_relation(self, value): self.sequence_relation.append(value) - def insert_sequence_relation(self, index, value): self.sequence_relation[index] = value - def get_property(self): return self.property - def set_property(self, property): self.property = property - def add_property(self, value): self.property.append(value) - def insert_property(self, index, value): self.property[index] = value - def get_rerootable(self): return self.rerootable - def set_rerootable(self, rerootable): self.rerootable = rerootable - def get_branch_length_unit(self): return self.branch_length_unit - def set_branch_length_unit(self, branch_length_unit): self.branch_length_unit = branch_length_unit - def get_type(self): return self.type_ - def set_type(self, type_): self.type_ = type_ - def get_rooted(self): return self.rooted - def set_rooted(self, rooted): self.rooted = rooted - def export(self, outfile, level, namespace_='phy:', name_='Phylogeny', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Phylogeny') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Phylogeny'): - if self.rerootable is not None and 'rerootable' not in already_processed: - already_processed.append('rerootable') - outfile.write(' rerootable="%s"' % self.gds_format_boolean(self.gds_str_lower(str(self.rerootable)), input_name='rerootable')) - if self.branch_length_unit is not None and 'branch_length_unit' not in already_processed: - already_processed.append('branch_length_unit') - outfile.write(' branch_length_unit=%s' % (self.gds_format_string(quote_attrib(self.branch_length_unit).encode(ExternalEncoding), input_name='branch_length_unit'), )) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), )) - if self.rooted is not None and 'rooted' not in already_processed: - already_processed.append('rooted') - outfile.write(' rooted="%s"' % self.gds_format_boolean(self.gds_str_lower(str(self.rooted)), input_name='rooted')) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Phylogeny', fromsubclass_=False): - if self.name is not None: - showIndent(outfile, level) - outfile.write('<%sname>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) - if self.id: - self.id.export(outfile, level, namespace_, name_='id') - if self.description is not None: - showIndent(outfile, level) - outfile.write('<%sdescription>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.description).encode(ExternalEncoding), input_name='description'), namespace_)) - if self.date is not None: - showIndent(outfile, level) - outfile.write('<%sdate>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.date).encode(ExternalEncoding), input_name='date'), namespace_)) - for confidence_ in self.confidence: - confidence_.export(outfile, level, namespace_, name_='confidence') - if self.clade: - self.clade.export(outfile, level, namespace_, name_='clade') - for clade_relation_ in self.clade_relation: - clade_relation_.export(outfile, level, namespace_, name_='clade_relation') - for sequence_relation_ in self.sequence_relation: - sequence_relation_.export(outfile, level, namespace_, name_='sequence_relation') - for property_ in self.property: - property_.export(outfile, level, namespace_, name_='property') - def hasContent_(self): - if ( - self.name is not None or - self.id is not None or - self.description is not None or - self.date is not None or - self.confidence or - self.clade is not None or - self.clade_relation or - self.sequence_relation or - self.property - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Phylogeny'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.rerootable is not None and 'rerootable' not in already_processed: - already_processed.append('rerootable') - showIndent(outfile, level) - outfile.write('rerootable = %s,\n' % (self.rerootable,)) - if self.branch_length_unit is not None and 'branch_length_unit' not in already_processed: - already_processed.append('branch_length_unit') - showIndent(outfile, level) - outfile.write('branch_length_unit = "%s",\n' % (self.branch_length_unit,)) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - showIndent(outfile, level) - outfile.write('type_ = "%s",\n' % (self.type_,)) - if self.rooted is not None and 'rooted' not in already_processed: - already_processed.append('rooted') - showIndent(outfile, level) - outfile.write('rooted = %s,\n' % (self.rooted,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.name is not None: - showIndent(outfile, level) - outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) - if self.id is not None: - showIndent(outfile, level) - outfile.write('id=model_.Id(\n') - self.id.exportLiteral(outfile, level, name_='id') - showIndent(outfile, level) - outfile.write('),\n') - if self.description is not None: - showIndent(outfile, level) - outfile.write('description=%s,\n' % quote_python(self.description).encode(ExternalEncoding)) - if self.date is not None: - showIndent(outfile, level) - outfile.write('date=%s,\n' % quote_python(self.date).encode(ExternalEncoding)) - showIndent(outfile, level) - outfile.write('confidence=[\n') - level += 1 - for confidence_ in self.confidence: - showIndent(outfile, level) - outfile.write('model_.Confidence(\n') - confidence_.exportLiteral(outfile, level, name_='Confidence') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.clade is not None: - showIndent(outfile, level) - outfile.write('clade=model_.Clade(\n') - self.clade.exportLiteral(outfile, level, name_='clade') - showIndent(outfile, level) - outfile.write('),\n') - showIndent(outfile, level) - outfile.write('clade_relation=[\n') - level += 1 - for clade_relation_ in self.clade_relation: - showIndent(outfile, level) - outfile.write('model_.CladeRelation(\n') - clade_relation_.exportLiteral(outfile, level, name_='CladeRelation') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('sequence_relation=[\n') - level += 1 - for sequence_relation_ in self.sequence_relation: - showIndent(outfile, level) - outfile.write('model_.SequenceRelation(\n') - sequence_relation_.exportLiteral(outfile, level, name_='SequenceRelation') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('property=[\n') - level += 1 - for property_ in self.property: - showIndent(outfile, level) - outfile.write('model_.Property(\n') - property_.exportLiteral(outfile, level, name_='Property') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('rerootable', node) - if value is not None and 'rerootable' not in already_processed: - already_processed.append('rerootable') - if value in ('true', '1'): - self.rerootable = True - elif value in ('false', '0'): - self.rerootable = False - else: - raise_parse_error(node, 'Bad boolean attribute') - value = find_attr_value_('branch_length_unit', node) - if value is not None and 'branch_length_unit' not in already_processed: - already_processed.append('branch_length_unit') - self.branch_length_unit = value - self.branch_length_unit = ' '.join(self.branch_length_unit.split()) - value = find_attr_value_('type', node) - if value is not None and 'type' not in already_processed: - already_processed.append('type') - self.type_ = value - self.type_ = ' '.join(self.type_.split()) - value = find_attr_value_('rooted', node) - if value is not None and 'rooted' not in already_processed: - already_processed.append('rooted') - if value in ('true', '1'): - self.rooted = True - elif value in ('false', '0'): - self.rooted = False - else: - raise_parse_error(node, 'Bad boolean attribute') - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'name': - name_ = child_.text - name_ = re_.sub(STRING_CLEANUP_PAT, " ", name_).strip() - name_ = self.gds_validate_string(name_, node, 'name') - self.name = name_ - elif nodeName_ == 'id': - obj_ = Id.factory() - obj_.build(child_) - self.set_id(obj_) - elif nodeName_ == 'description': - description_ = child_.text - description_ = re_.sub(STRING_CLEANUP_PAT, " ", description_).strip() - description_ = self.gds_validate_string(description_, node, 'description') - self.description = description_ - elif nodeName_ == 'date': - date_ = child_.text - date_ = self.gds_validate_string(date_, node, 'date') - self.date = date_ - elif nodeName_ == 'confidence': - obj_ = Confidence.factory() - obj_.build(child_) - self.confidence.append(obj_) - elif nodeName_ == 'clade': - obj_ = Clade.factory() - obj_.build(child_) - self.set_clade(obj_) - elif nodeName_ == 'clade_relation': - obj_ = CladeRelation.factory() - obj_.build(child_) - self.clade_relation.append(obj_) - elif nodeName_ == 'sequence_relation': - obj_ = SequenceRelation.factory() - obj_.build(child_) - self.sequence_relation.append(obj_) - elif nodeName_ == 'property': - obj_ = Property.factory() - obj_.build(child_) - self.property.append(obj_) -# end class Phylogeny - - -class Clade(GeneratedsSuper): - """Element Clade is used in a recursive manner to describe the topology - of a phylogenetic tree. The parent branch length of a clade can - be described either with the 'branch_length' element or the - 'branch_length' attribute (it is not recommended to use both at - the same time, though). Usage of the 'branch_length' attribute - allows for a less verbose description. Element 'confidence' is - used to indicate the support for a clade/parent branch. Element - 'events' is used to describe such events as gene-duplications at - the root node/parent branch of a clade. Element 'width' is the - branch width for this clade (including parent branch). Both - 'color' and 'width' elements apply for the whole clade unless - overwritten in-sub clades. Attribute 'id_source' is used to link - other elements to a clade (on the xml-level).""" - subclass = None - superclass = None - def __init__(self, id_source=None, branch_length_attr=None, name=None, branch_length=None, confidence=None, width=None, color=None, node_id=None, taxonomy=None, sequence=None, events=None, binary_characters=None, distribution=None, date=None, reference=None, property=None, clade=None, valueOf_=None): - self.id_source = _cast(None, id_source) - self.branch_length_attr = _cast(None, branch_length_attr) - self.name = name - self.branch_length = branch_length - if confidence is None: - self.confidence = [] - else: - self.confidence = confidence - self.width = width - self.color = color - self.node_id = node_id - if taxonomy is None: - self.taxonomy = [] - else: - self.taxonomy = taxonomy - if sequence is None: - self.sequence = [] - else: - self.sequence = sequence - self.events = events - self.binary_characters = binary_characters - if distribution is None: - self.distribution = [] - else: - self.distribution = distribution - self.date = date - if reference is None: - self.reference = [] - else: - self.reference = reference - if property is None: - self.property = [] - else: - self.property = property - if clade is None: - self.clade = [] - else: - self.clade = clade - def factory(*args_, **kwargs_): - if Clade.subclass: - return Clade.subclass(*args_, **kwargs_) - else: - return Clade(*args_, **kwargs_) - factory = staticmethod(factory) - def get_name(self): return self.name - def set_name(self, name): self.name = name - def get_branch_length(self): return self.branch_length - def set_branch_length(self, branch_length): self.branch_length = branch_length - def get_confidence(self): return self.confidence - def set_confidence(self, confidence): self.confidence = confidence - def add_confidence(self, value): self.confidence.append(value) - def insert_confidence(self, index, value): self.confidence[index] = value - def get_width(self): return self.width - def set_width(self, width): self.width = width - def get_color(self): return self.color - def set_color(self, color): self.color = color - def get_node_id(self): return self.node_id - def set_node_id(self, node_id): self.node_id = node_id - def get_taxonomy(self): return self.taxonomy - def set_taxonomy(self, taxonomy): self.taxonomy = taxonomy - def add_taxonomy(self, value): self.taxonomy.append(value) - def insert_taxonomy(self, index, value): self.taxonomy[index] = value - def get_sequence(self): return self.sequence - def set_sequence(self, sequence): self.sequence = sequence - def add_sequence(self, value): self.sequence.append(value) - def insert_sequence(self, index, value): self.sequence[index] = value - def get_events(self): return self.events - def set_events(self, events): self.events = events - def get_binary_characters(self): return self.binary_characters - def set_binary_characters(self, binary_characters): self.binary_characters = binary_characters - def get_distribution(self): return self.distribution - def set_distribution(self, distribution): self.distribution = distribution - def add_distribution(self, value): self.distribution.append(value) - def insert_distribution(self, index, value): self.distribution[index] = value - def get_date(self): return self.date - def set_date(self, date): self.date = date - def get_reference(self): return self.reference - def set_reference(self, reference): self.reference = reference - def add_reference(self, value): self.reference.append(value) - def insert_reference(self, index, value): self.reference[index] = value - def get_property(self): return self.property - def set_property(self, property): self.property = property - def add_property(self, value): self.property.append(value) - def insert_property(self, index, value): self.property[index] = value - def get_clade(self): return self.clade - def set_clade(self, clade): self.clade = clade - def add_clade(self, value): self.clade.append(value) - def insert_clade(self, index, value): self.clade[index] = value - def get_id_source(self): return self.id_source - def set_id_source(self, id_source): self.id_source = id_source - def get_branch_length_attr(self): return self.branch_length_attr - def set_branch_length_attr(self, branch_length_attr): self.branch_length_attr = branch_length_attr - def export(self, outfile, level, namespace_='phy:', name_='Clade', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Clade') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Clade'): - if self.id_source is not None and 'id_source' not in already_processed: - already_processed.append('id_source') - outfile.write(' id_source=%s' % (quote_attrib(self.id_source), )) - if self.branch_length_attr is not None and 'branch_length_attr' not in already_processed: - already_processed.append('branch_length_attr') - outfile.write(' branch_length_attr=%s' % (self.gds_format_string(quote_attrib(self.branch_length_attr).encode(ExternalEncoding), input_name='branch_length_attr'), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Clade', fromsubclass_=False): - if self.name is not None: - showIndent(outfile, level) - outfile.write('<%sname>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) - if self.branch_length is not None: - showIndent(outfile, level) - outfile.write('<%sbranch_length>%s\n' % (namespace_, self.gds_format_double(self.branch_length, input_name='branch_length'), namespace_)) - for confidence_ in self.confidence: - confidence_.export(outfile, level, namespace_, name_='confidence') - if self.width is not None: - showIndent(outfile, level) - outfile.write('<%swidth>%s\n' % (namespace_, self.gds_format_double(self.width, input_name='width'), namespace_)) - if self.color: - self.color.export(outfile, level, namespace_, name_='color') - if self.node_id: - self.node_id.export(outfile, level, namespace_, name_='node_id') - for taxonomy_ in self.taxonomy: - taxonomy_.export(outfile, level, namespace_, name_='taxonomy') - for sequence_ in self.sequence: - sequence_.export(outfile, level, namespace_, name_='sequence') - if self.events: - self.events.export(outfile, level, namespace_, name_='events') - if self.binary_characters: - self.binary_characters.export(outfile, level, namespace_, name_='binary_characters') - for distribution_ in self.distribution: - distribution_.export(outfile, level, namespace_, name_='distribution') - if self.date: - self.date.export(outfile, level, namespace_, name_='date') - for reference_ in self.reference: - reference_.export(outfile, level, namespace_, name_='reference') - for property_ in self.property: - property_.export(outfile, level, namespace_, name_='property') - for clade_ in self.clade: - clade_.export(outfile, level, namespace_, name_='clade') - def hasContent_(self): - if ( - self.name is not None or - self.branch_length is not None or - self.confidence or - self.width is not None or - self.color is not None or - self.node_id is not None or - self.taxonomy or - self.sequence or - self.events is not None or - self.binary_characters is not None or - self.distribution or - self.date is not None or - self.reference or - self.property or - self.clade - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Clade'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.id_source is not None and 'id_source' not in already_processed: - already_processed.append('id_source') - showIndent(outfile, level) - outfile.write('id_source = %s,\n' % (self.id_source,)) - if self.branch_length_attr is not None and 'branch_length_attr' not in already_processed: - already_processed.append('branch_length_attr') - showIndent(outfile, level) - outfile.write('branch_length_attr = "%s",\n' % (self.branch_length_attr,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.name is not None: - showIndent(outfile, level) - outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) - if self.branch_length is not None: - showIndent(outfile, level) - outfile.write('branch_length=%e,\n' % self.branch_length) - showIndent(outfile, level) - outfile.write('confidence=[\n') - level += 1 - for confidence_ in self.confidence: - showIndent(outfile, level) - outfile.write('model_.Confidence(\n') - confidence_.exportLiteral(outfile, level, name_='Confidence') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.width is not None: - showIndent(outfile, level) - outfile.write('width=%e,\n' % self.width) - if self.color is not None: - showIndent(outfile, level) - outfile.write('color=model_.BranchColor(\n') - self.color.exportLiteral(outfile, level, name_='color') - showIndent(outfile, level) - outfile.write('),\n') - if self.node_id is not None: - showIndent(outfile, level) - outfile.write('node_id=model_.Id(\n') - self.node_id.exportLiteral(outfile, level, name_='node_id') - showIndent(outfile, level) - outfile.write('),\n') - showIndent(outfile, level) - outfile.write('taxonomy=[\n') - level += 1 - for taxonomy_ in self.taxonomy: - showIndent(outfile, level) - outfile.write('model_.Taxonomy(\n') - taxonomy_.exportLiteral(outfile, level, name_='Taxonomy') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('sequence=[\n') - level += 1 - for sequence_ in self.sequence: - showIndent(outfile, level) - outfile.write('model_.Sequence(\n') - sequence_.exportLiteral(outfile, level, name_='Sequence') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.events is not None: - showIndent(outfile, level) - outfile.write('events=model_.Events(\n') - self.events.exportLiteral(outfile, level, name_='events') - showIndent(outfile, level) - outfile.write('),\n') - if self.binary_characters is not None: - showIndent(outfile, level) - outfile.write('binary_characters=model_.BinaryCharacters(\n') - self.binary_characters.exportLiteral(outfile, level, name_='binary_characters') - showIndent(outfile, level) - outfile.write('),\n') - showIndent(outfile, level) - outfile.write('distribution=[\n') - level += 1 - for distribution_ in self.distribution: - showIndent(outfile, level) - outfile.write('model_.Distribution(\n') - distribution_.exportLiteral(outfile, level, name_='Distribution') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.date is not None: - showIndent(outfile, level) - outfile.write('date=model_.Date(\n') - self.date.exportLiteral(outfile, level, name_='date') - showIndent(outfile, level) - outfile.write('),\n') - showIndent(outfile, level) - outfile.write('reference=[\n') - level += 1 - for reference_ in self.reference: - showIndent(outfile, level) - outfile.write('model_.Reference(\n') - reference_.exportLiteral(outfile, level, name_='Reference') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('property=[\n') - level += 1 - for property_ in self.property: - showIndent(outfile, level) - outfile.write('model_.Property(\n') - property_.exportLiteral(outfile, level, name_='Property') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('clade=[\n') - level += 1 - for clade_ in self.clade: - showIndent(outfile, level) - outfile.write('model_.Clade(\n') - clade_.exportLiteral(outfile, level, name_='Clade') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('id_source', node) - if value is not None and 'id_source' not in already_processed: - already_processed.append('id_source') - self.id_source = value - value = find_attr_value_('branch_length_attr', node) - if value is not None and 'branch_length_attr' not in already_processed: - already_processed.append('branch_length_attr') - self.branch_length_attr = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'name': - name_ = child_.text - name_ = re_.sub(STRING_CLEANUP_PAT, " ", name_).strip() - name_ = self.gds_validate_string(name_, node, 'name') - self.name = name_ - elif nodeName_ == 'branch_length': - sval_ = child_.text - try: - fval_ = float(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires float or double: %s' % exp) - fval_ = self.gds_validate_float(fval_, node, 'branch_length') - self.branch_length = fval_ - elif nodeName_ == 'confidence': - obj_ = Confidence.factory() - obj_.build(child_) - self.confidence.append(obj_) - elif nodeName_ == 'width': - sval_ = child_.text - try: - fval_ = float(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires float or double: %s' % exp) - fval_ = self.gds_validate_float(fval_, node, 'width') - self.width = fval_ - elif nodeName_ == 'color': - obj_ = BranchColor.factory() - obj_.build(child_) - self.set_color(obj_) - elif nodeName_ == 'node_id': - obj_ = Id.factory() - obj_.build(child_) - self.set_node_id(obj_) - elif nodeName_ == 'taxonomy': - obj_ = Taxonomy.factory() - obj_.build(child_) - self.taxonomy.append(obj_) - elif nodeName_ == 'sequence': - obj_ = Sequence.factory() - obj_.build(child_) - self.sequence.append(obj_) - elif nodeName_ == 'events': - obj_ = Events.factory() - obj_.build(child_) - self.set_events(obj_) - elif nodeName_ == 'binary_characters': - obj_ = BinaryCharacters.factory() - obj_.build(child_) - self.set_binary_characters(obj_) - elif nodeName_ == 'distribution': - obj_ = Distribution.factory() - obj_.build(child_) - self.distribution.append(obj_) - elif nodeName_ == 'date': - obj_ = Date.factory() - obj_.build(child_) - self.set_date(obj_) - elif nodeName_ == 'reference': - obj_ = Reference.factory() - obj_.build(child_) - self.reference.append(obj_) - elif nodeName_ == 'property': - obj_ = Property.factory() - obj_.build(child_) - self.property.append(obj_) - elif nodeName_ == 'clade': - obj_ = Clade.factory() - obj_.build(child_) - self.clade.append(obj_) -# end class Clade - - -class Taxonomy(GeneratedsSuper): - """Element Taxonomy is used to describe taxonomic information for a - clade. Element 'code' is intended to store UniProt/Swiss-Prot - style organism codes (e.g. 'APLCA' for the California sea hare - 'Aplysia californica') or other styles of mnemonics (e.g. - 'Aca'). Element 'authority' is used to keep the authority, such - as 'J. G. Cooper, 1863', associated with the 'scientific_name'. - Element 'id' is used for a unique identifier of a taxon (for - example '6500' with 'ncbi_taxonomy' as 'provider' for the - California sea hare). Attribute 'id_source' is used to link - other elements to a taxonomy (on the xml-level).""" - subclass = None - superclass = None - def __init__(self, id_source=None, id=None, code=None, scientific_name=None, authority=None, common_name=None, synonym=None, rank=None, uri=None, valueOf_=None): - self.id_source = _cast(None, id_source) - self.id = id - self.code = code - self.scientific_name = scientific_name - self.authority = authority - if common_name is None: - self.common_name = [] - else: - self.common_name = common_name - if synonym is None: - self.synonym = [] - else: - self.synonym = synonym - self.rank = rank - self.uri = uri - def factory(*args_, **kwargs_): - if Taxonomy.subclass: - return Taxonomy.subclass(*args_, **kwargs_) - else: - return Taxonomy(*args_, **kwargs_) - factory = staticmethod(factory) - def get_id(self): return self.id - def set_id(self, id): self.id = id - def get_code(self): return self.code - def set_code(self, code): self.code = code - def validate_TaxonomyCode(self, value): - # Validate type TaxonomyCode, a restriction on xs:token. - pass - def get_scientific_name(self): return self.scientific_name - def set_scientific_name(self, scientific_name): self.scientific_name = scientific_name - def get_authority(self): return self.authority - def set_authority(self, authority): self.authority = authority - def get_common_name(self): return self.common_name - def set_common_name(self, common_name): self.common_name = common_name - def add_common_name(self, value): self.common_name.append(value) - def insert_common_name(self, index, value): self.common_name[index] = value - def get_synonym(self): return self.synonym - def set_synonym(self, synonym): self.synonym = synonym - def add_synonym(self, value): self.synonym.append(value) - def insert_synonym(self, index, value): self.synonym[index] = value - def get_rank(self): return self.rank - def set_rank(self, rank): self.rank = rank - def validate_Rank(self, value): - # Validate type Rank, a restriction on xs:token. - pass - def get_uri(self): return self.uri - def set_uri(self, uri): self.uri = uri - def get_id_source(self): return self.id_source - def set_id_source(self, id_source): self.id_source = id_source - def export(self, outfile, level, namespace_='phy:', name_='Taxonomy', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Taxonomy') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Taxonomy'): - if self.id_source is not None and 'id_source' not in already_processed: - already_processed.append('id_source') - outfile.write(' id_source=%s' % (quote_attrib(self.id_source), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Taxonomy', fromsubclass_=False): - if self.id: - self.id.export(outfile, level, namespace_, name_='id') - if self.code is not None: - showIndent(outfile, level) - outfile.write('<%scode>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.code).encode(ExternalEncoding), input_name='code'), namespace_)) - if self.scientific_name is not None: - showIndent(outfile, level) - outfile.write('<%sscientific_name>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.scientific_name).encode(ExternalEncoding), input_name='scientific_name'), namespace_)) - if self.authority is not None: - showIndent(outfile, level) - outfile.write('<%sauthority>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.authority).encode(ExternalEncoding), input_name='authority'), namespace_)) - for common_name_ in self.common_name: - showIndent(outfile, level) - outfile.write('<%scommon_name>%s\n' % (namespace_, self.gds_format_string(quote_xml(common_name_).encode(ExternalEncoding), input_name='common_name'), namespace_)) - for synonym_ in self.synonym: - showIndent(outfile, level) - outfile.write('<%ssynonym>%s\n' % (namespace_, self.gds_format_string(quote_xml(synonym_).encode(ExternalEncoding), input_name='synonym'), namespace_)) - if self.rank is not None: - showIndent(outfile, level) - outfile.write('<%srank>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.rank).encode(ExternalEncoding), input_name='rank'), namespace_)) - if self.uri: - self.uri.export(outfile, level, namespace_, name_='uri') - def hasContent_(self): - if ( - self.id is not None or - self.code is not None or - self.scientific_name is not None or - self.authority is not None or - self.common_name or - self.synonym or - self.rank is not None or - self.uri is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Taxonomy'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.id_source is not None and 'id_source' not in already_processed: - already_processed.append('id_source') - showIndent(outfile, level) - outfile.write('id_source = %s,\n' % (self.id_source,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.id is not None: - showIndent(outfile, level) - outfile.write('id=model_.Id(\n') - self.id.exportLiteral(outfile, level, name_='id') - showIndent(outfile, level) - outfile.write('),\n') - if self.code is not None: - showIndent(outfile, level) - outfile.write('code=%s,\n' % quote_python(self.code).encode(ExternalEncoding)) - if self.scientific_name is not None: - showIndent(outfile, level) - outfile.write('scientific_name=%s,\n' % quote_python(self.scientific_name).encode(ExternalEncoding)) - if self.authority is not None: - showIndent(outfile, level) - outfile.write('authority=%s,\n' % quote_python(self.authority).encode(ExternalEncoding)) - showIndent(outfile, level) - outfile.write('common_name=[\n') - level += 1 - for common_name_ in self.common_name: - showIndent(outfile, level) - outfile.write('%s,\n' % quote_python(common_name_).encode(ExternalEncoding)) - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('synonym=[\n') - level += 1 - for synonym_ in self.synonym: - showIndent(outfile, level) - outfile.write('%s,\n' % quote_python(synonym_).encode(ExternalEncoding)) - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.rank is not None: - showIndent(outfile, level) - outfile.write('rank=%s,\n' % quote_python(self.rank).encode(ExternalEncoding)) - if self.uri is not None: - showIndent(outfile, level) - outfile.write('uri=model_.Uri(\n') - self.uri.exportLiteral(outfile, level, name_='uri') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('id_source', node) - if value is not None and 'id_source' not in already_processed: - already_processed.append('id_source') - self.id_source = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'id': - obj_ = Id.factory() - obj_.build(child_) - self.set_id(obj_) - elif nodeName_ == 'code': - code_ = child_.text - code_ = re_.sub(STRING_CLEANUP_PAT, " ", code_).strip() - code_ = self.gds_validate_string(code_, node, 'code') - self.code = code_ - self.validate_TaxonomyCode(self.code) # validate type TaxonomyCode - elif nodeName_ == 'scientific_name': - scientific_name_ = child_.text - scientific_name_ = re_.sub(STRING_CLEANUP_PAT, " ", scientific_name_).strip() - scientific_name_ = self.gds_validate_string(scientific_name_, node, 'scientific_name') - self.scientific_name = scientific_name_ - elif nodeName_ == 'authority': - authority_ = child_.text - authority_ = re_.sub(STRING_CLEANUP_PAT, " ", authority_).strip() - authority_ = self.gds_validate_string(authority_, node, 'authority') - self.authority = authority_ - elif nodeName_ == 'common_name': - common_name_ = child_.text - common_name_ = re_.sub(STRING_CLEANUP_PAT, " ", common_name_).strip() - common_name_ = self.gds_validate_string(common_name_, node, 'common_name') - self.common_name.append(common_name_) - elif nodeName_ == 'synonym': - synonym_ = child_.text - synonym_ = re_.sub(STRING_CLEANUP_PAT, " ", synonym_).strip() - synonym_ = self.gds_validate_string(synonym_, node, 'synonym') - self.synonym.append(synonym_) - elif nodeName_ == 'rank': - rank_ = child_.text - rank_ = re_.sub(STRING_CLEANUP_PAT, " ", rank_).strip() - rank_ = self.gds_validate_string(rank_, node, 'rank') - self.rank = rank_ - self.validate_Rank(self.rank) # validate type Rank - elif nodeName_ == 'uri': - obj_ = Uri.factory() - obj_.build(child_) - self.set_uri(obj_) -# end class Taxonomy - - -class Sequence(GeneratedsSuper): - """Element Sequence is used to represent a molecular sequence (Protein, - DNA, RNA) associated with a node. 'symbol' is a short (maximal - ten characters) symbol of the sequence (e.g. 'ACTM') whereas - 'name' is used for the full name (e.g. 'muscle Actin'). - 'location' is used for the location of a sequence on a - genome/chromosome. The actual sequence can be stored with the - 'mol_seq' element. Attribute 'type' is used to indicate the type - of sequence ('dna', 'rna', or 'protein'). One intended use for - 'id_ref' is to link a sequence to a taxonomy (via the taxonomy's - 'id_source') in case of multiple sequences and taxonomies per - node.""" - subclass = None - superclass = None - def __init__(self, id_source=None, id_ref=None, type_=None, symbol=None, accession=None, name=None, location=None, mol_seq=None, uri=None, annotation=None, domain_architecture=None, valueOf_=None): - self.id_source = _cast(None, id_source) - self.id_ref = _cast(None, id_ref) - self.type_ = _cast(None, type_) - self.symbol = symbol - self.accession = accession - self.name = name - self.location = location - self.mol_seq = mol_seq - self.uri = uri - if annotation is None: - self.annotation = [] - else: - self.annotation = annotation - self.domain_architecture = domain_architecture - def factory(*args_, **kwargs_): - if Sequence.subclass: - return Sequence.subclass(*args_, **kwargs_) - else: - return Sequence(*args_, **kwargs_) - factory = staticmethod(factory) - def get_symbol(self): return self.symbol - def set_symbol(self, symbol): self.symbol = symbol - def validate_SequenceSymbol(self, value): - # Validate type SequenceSymbol, a restriction on xs:token. - pass - def get_accession(self): return self.accession - def set_accession(self, accession): self.accession = accession - def get_name(self): return self.name - def set_name(self, name): self.name = name - def get_location(self): return self.location - def set_location(self, location): self.location = location - def get_mol_seq(self): return self.mol_seq - def set_mol_seq(self, mol_seq): self.mol_seq = mol_seq - def get_uri(self): return self.uri - def set_uri(self, uri): self.uri = uri - def get_annotation(self): return self.annotation - def set_annotation(self, annotation): self.annotation = annotation - def add_annotation(self, value): self.annotation.append(value) - def insert_annotation(self, index, value): self.annotation[index] = value - def get_domain_architecture(self): return self.domain_architecture - def set_domain_architecture(self, domain_architecture): self.domain_architecture = domain_architecture - def get_id_source(self): return self.id_source - def set_id_source(self, id_source): self.id_source = id_source - def get_id_ref(self): return self.id_ref - def set_id_ref(self, id_ref): self.id_ref = id_ref - def get_type(self): return self.type_ - def set_type(self, type_): self.type_ = type_ - def export(self, outfile, level, namespace_='phy:', name_='Sequence', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Sequence') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Sequence'): - if self.id_source is not None and 'id_source' not in already_processed: - already_processed.append('id_source') - outfile.write(' id_source=%s' % (quote_attrib(self.id_source), )) - if self.id_ref is not None and 'id_ref' not in already_processed: - already_processed.append('id_ref') - outfile.write(' id_ref=%s' % (quote_attrib(self.id_ref), )) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - outfile.write(' type=%s' % (quote_attrib(self.type_), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Sequence', fromsubclass_=False): - if self.symbol is not None: - showIndent(outfile, level) - outfile.write('<%ssymbol>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.symbol).encode(ExternalEncoding), input_name='symbol'), namespace_)) - if self.accession: - self.accession.export(outfile, level, namespace_, name_='accession') - if self.name is not None: - showIndent(outfile, level) - outfile.write('<%sname>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) - if self.location is not None: - showIndent(outfile, level) - outfile.write('<%slocation>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.location).encode(ExternalEncoding), input_name='location'), namespace_)) - if self.mol_seq: - self.mol_seq.export(outfile, level, namespace_, name_='mol_seq') - if self.uri: - self.uri.export(outfile, level, namespace_, name_='uri') - for annotation_ in self.annotation: - annotation_.export(outfile, level, namespace_, name_='annotation') - if self.domain_architecture: - self.domain_architecture.export(outfile, level, namespace_, name_='domain_architecture') - def hasContent_(self): - if ( - self.symbol is not None or - self.accession is not None or - self.name is not None or - self.location is not None or - self.mol_seq is not None or - self.uri is not None or - self.annotation or - self.domain_architecture is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Sequence'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.id_source is not None and 'id_source' not in already_processed: - already_processed.append('id_source') - showIndent(outfile, level) - outfile.write('id_source = %s,\n' % (self.id_source,)) - if self.id_ref is not None and 'id_ref' not in already_processed: - already_processed.append('id_ref') - showIndent(outfile, level) - outfile.write('id_ref = %s,\n' % (self.id_ref,)) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - showIndent(outfile, level) - outfile.write('type_ = %s,\n' % (self.type_,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.symbol is not None: - showIndent(outfile, level) - outfile.write('symbol=%s,\n' % quote_python(self.symbol).encode(ExternalEncoding)) - if self.accession is not None: - showIndent(outfile, level) - outfile.write('accession=model_.Accession(\n') - self.accession.exportLiteral(outfile, level, name_='accession') - showIndent(outfile, level) - outfile.write('),\n') - if self.name is not None: - showIndent(outfile, level) - outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) - if self.location is not None: - showIndent(outfile, level) - outfile.write('location=%s,\n' % quote_python(self.location).encode(ExternalEncoding)) - if self.mol_seq is not None: - showIndent(outfile, level) - outfile.write('mol_seq=model_.MolSeq(\n') - self.mol_seq.exportLiteral(outfile, level, name_='mol_seq') - showIndent(outfile, level) - outfile.write('),\n') - if self.uri is not None: - showIndent(outfile, level) - outfile.write('uri=model_.Uri(\n') - self.uri.exportLiteral(outfile, level, name_='uri') - showIndent(outfile, level) - outfile.write('),\n') - showIndent(outfile, level) - outfile.write('annotation=[\n') - level += 1 - for annotation_ in self.annotation: - showIndent(outfile, level) - outfile.write('model_.Annotation(\n') - annotation_.exportLiteral(outfile, level, name_='Annotation') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.domain_architecture is not None: - showIndent(outfile, level) - outfile.write('domain_architecture=model_.DomainArchitecture(\n') - self.domain_architecture.exportLiteral(outfile, level, name_='domain_architecture') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('id_source', node) - if value is not None and 'id_source' not in already_processed: - already_processed.append('id_source') - self.id_source = value - value = find_attr_value_('id_ref', node) - if value is not None and 'id_ref' not in already_processed: - already_processed.append('id_ref') - self.id_ref = value - value = find_attr_value_('type', node) - if value is not None and 'type' not in already_processed: - already_processed.append('type') - self.type_ = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'symbol': - symbol_ = child_.text - symbol_ = re_.sub(STRING_CLEANUP_PAT, " ", symbol_).strip() - symbol_ = self.gds_validate_string(symbol_, node, 'symbol') - self.symbol = symbol_ - self.validate_SequenceSymbol(self.symbol) # validate type SequenceSymbol - elif nodeName_ == 'accession': - obj_ = Accession.factory() - obj_.build(child_) - self.set_accession(obj_) - elif nodeName_ == 'name': - name_ = child_.text - name_ = re_.sub(STRING_CLEANUP_PAT, " ", name_).strip() - name_ = self.gds_validate_string(name_, node, 'name') - self.name = name_ - elif nodeName_ == 'location': - location_ = child_.text - location_ = re_.sub(STRING_CLEANUP_PAT, " ", location_).strip() - location_ = self.gds_validate_string(location_, node, 'location') - self.location = location_ - elif nodeName_ == 'mol_seq': - obj_ = MolSeq.factory() - obj_.build(child_) - self.set_mol_seq(obj_) - elif nodeName_ == 'uri': - obj_ = Uri.factory() - obj_.build(child_) - self.set_uri(obj_) - elif nodeName_ == 'annotation': - obj_ = Annotation.factory() - obj_.build(child_) - self.annotation.append(obj_) - elif nodeName_ == 'domain_architecture': - obj_ = DomainArchitecture.factory() - obj_.build(child_) - self.set_domain_architecture(obj_) -# end class Sequence - - -class MolSeq(GeneratedsSuper): - """Element 'mol_seq' is used to store molecular sequences. The - 'is_aligned' attribute is used to indicated that this molecular - sequence is aligned with all other sequences in the same - phylogeny for which 'is aligned' is true as well (which, in most - cases, means that gaps were introduced, and that all sequences - for which 'is aligned' is true must have the same length).""" - subclass = None - superclass = None - def __init__(self, is_aligned=None, valueOf_=None): - self.is_aligned = _cast(bool, is_aligned) - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if MolSeq.subclass: - return MolSeq.subclass(*args_, **kwargs_) - else: - return MolSeq(*args_, **kwargs_) - factory = staticmethod(factory) - def get_is_aligned(self): return self.is_aligned - def set_is_aligned(self, is_aligned): self.is_aligned = is_aligned - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def export(self, outfile, level, namespace_='phy:', name_='MolSeq', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='MolSeq') - if self.hasContent_(): - outfile.write('>') - outfile.write(str(self.valueOf_).encode(ExternalEncoding)) - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='MolSeq'): - if self.is_aligned is not None and 'is_aligned' not in already_processed: - already_processed.append('is_aligned') - outfile.write(' is_aligned="%s"' % self.gds_format_boolean(self.gds_str_lower(str(self.is_aligned)), input_name='is_aligned')) - def exportChildren(self, outfile, level, namespace_='phy:', name_='MolSeq', fromsubclass_=False): - pass - def hasContent_(self): - if ( - self.valueOf_ - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='MolSeq'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.is_aligned is not None and 'is_aligned' not in already_processed: - already_processed.append('is_aligned') - showIndent(outfile, level) - outfile.write('is_aligned = %s,\n' % (self.is_aligned,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - self.valueOf_ = get_all_text_(node) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('is_aligned', node) - if value is not None and 'is_aligned' not in already_processed: - already_processed.append('is_aligned') - if value in ('true', '1'): - self.is_aligned = True - elif value in ('false', '0'): - self.is_aligned = False - else: - raise_parse_error(node, 'Bad boolean attribute') - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class MolSeq - - -class Accession(GeneratedsSuper): - """Element Accession is used to capture the local part in a sequence - identifier (e.g. 'P17304' in 'UniProtKB:P17304', in which case - the 'source' attribute would be 'UniProtKB').""" - subclass = None - superclass = None - def __init__(self, source=None, valueOf_=None): - self.source = _cast(None, source) - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if Accession.subclass: - return Accession.subclass(*args_, **kwargs_) - else: - return Accession(*args_, **kwargs_) - factory = staticmethod(factory) - def get_source(self): return self.source - def set_source(self, source): self.source = source - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def export(self, outfile, level, namespace_='phy:', name_='Accession', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Accession') - if self.hasContent_(): - outfile.write('>') - outfile.write(str(self.valueOf_).encode(ExternalEncoding)) - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Accession'): - if self.source is not None and 'source' not in already_processed: - already_processed.append('source') - outfile.write(' source=%s' % (self.gds_format_string(quote_attrib(self.source).encode(ExternalEncoding), input_name='source'), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Accession', fromsubclass_=False): - pass - def hasContent_(self): - if ( - self.valueOf_ - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Accession'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.source is not None and 'source' not in already_processed: - already_processed.append('source') - showIndent(outfile, level) - outfile.write('source = "%s",\n' % (self.source,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - self.valueOf_ = get_all_text_(node) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('source', node) - if value is not None and 'source' not in already_processed: - already_processed.append('source') - self.source = value - self.source = ' '.join(self.source.split()) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class Accession - - -class DomainArchitecture(GeneratedsSuper): - """This is used describe the domain architecture of a protein. - Attribute 'length' is the total length of the protein""" - subclass = None - superclass = None - def __init__(self, length=None, domain=None, valueOf_=None): - self.length = _cast(int, length) - if domain is None: - self.domain = [] - else: - self.domain = domain - def factory(*args_, **kwargs_): - if DomainArchitecture.subclass: - return DomainArchitecture.subclass(*args_, **kwargs_) - else: - return DomainArchitecture(*args_, **kwargs_) - factory = staticmethod(factory) - def get_domain(self): return self.domain - def set_domain(self, domain): self.domain = domain - def add_domain(self, value): self.domain.append(value) - def insert_domain(self, index, value): self.domain[index] = value - def get_length(self): return self.length - def set_length(self, length): self.length = length - def export(self, outfile, level, namespace_='phy:', name_='DomainArchitecture', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='DomainArchitecture') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='DomainArchitecture'): - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - outfile.write(' length="%s"' % self.gds_format_integer(self.length, input_name='length')) - def exportChildren(self, outfile, level, namespace_='phy:', name_='DomainArchitecture', fromsubclass_=False): - for domain_ in self.domain: - domain_.export(outfile, level, namespace_, name_='domain') - def hasContent_(self): - if ( - self.domain - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='DomainArchitecture'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.length is not None and 'length' not in already_processed: - already_processed.append('length') - showIndent(outfile, level) - outfile.write('length = %d,\n' % (self.length,)) - def exportLiteralChildren(self, outfile, level, name_): - showIndent(outfile, level) - outfile.write('domain=[\n') - level += 1 - for domain_ in self.domain: - showIndent(outfile, level) - outfile.write('model_.ProteinDomain(\n') - domain_.exportLiteral(outfile, level, name_='ProteinDomain') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('length', node) - if value is not None and 'length' not in already_processed: - already_processed.append('length') - try: - self.length = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.length < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'domain': - obj_ = ProteinDomain.factory() - obj_.build(child_) - self.domain.append(obj_) -# end class DomainArchitecture - - -class ProteinDomain(GeneratedsSuper): - """To represent an individual domain in a domain architecture. The - name/unique identifier is described via the 'id' attribute. - 'confidence' can be used to store (i.e.) E-values.""" - subclass = None - superclass = None - def __init__(self, to=None, confidence=None, fromxx=None, id=None, valueOf_=None): - self.to = _cast(int, to) - self.confidence = _cast(float, confidence) - self.fromxx = _cast(int, fromxx) - self.id = _cast(None, id) - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if ProteinDomain.subclass: - return ProteinDomain.subclass(*args_, **kwargs_) - else: - return ProteinDomain(*args_, **kwargs_) - factory = staticmethod(factory) - def get_to(self): return self.to - def set_to(self, to): self.to = to - def get_confidence(self): return self.confidence - def set_confidence(self, confidence): self.confidence = confidence - def get_from(self): return self.fromxx - def set_from(self, fromxx): self.fromxx = fromxx - def get_id(self): return self.id - def set_id(self, id): self.id = id - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def export(self, outfile, level, namespace_='phy:', name_='ProteinDomain', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='ProteinDomain') - if self.hasContent_(): - outfile.write('>') - outfile.write(str(self.valueOf_).encode(ExternalEncoding)) - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='ProteinDomain'): - if self.to is not None and 'to' not in already_processed: - already_processed.append('to') - outfile.write(' to="%s"' % self.gds_format_integer(self.to, input_name='to')) - if self.confidence is not None and 'confidence' not in already_processed: - already_processed.append('confidence') - outfile.write(' confidence="%s"' % self.gds_format_double(self.confidence, input_name='confidence')) - if self.fromxx is not None and 'fromxx' not in already_processed: - already_processed.append('fromxx') - outfile.write(' from="%s"' % self.gds_format_integer(self.fromxx, input_name='from')) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='ProteinDomain', fromsubclass_=False): - pass - def hasContent_(self): - if ( - self.valueOf_ - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='ProteinDomain'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.to is not None and 'to' not in already_processed: - already_processed.append('to') - showIndent(outfile, level) - outfile.write('to = %d,\n' % (self.to,)) - if self.confidence is not None and 'confidence' not in already_processed: - already_processed.append('confidence') - showIndent(outfile, level) - outfile.write('confidence = %e,\n' % (self.confidence,)) - if self.fromxx is not None and 'fromxx' not in already_processed: - already_processed.append('fromxx') - showIndent(outfile, level) - outfile.write('fromxx = %d,\n' % (self.fromxx,)) - if self.id is not None and 'id' not in already_processed: - already_processed.append('id') - showIndent(outfile, level) - outfile.write('id = "%s",\n' % (self.id,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - self.valueOf_ = get_all_text_(node) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('to', node) - if value is not None and 'to' not in already_processed: - already_processed.append('to') - try: - self.to = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.to < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - value = find_attr_value_('confidence', node) - if value is not None and 'confidence' not in already_processed: - already_processed.append('confidence') - try: - self.confidence = float(value) - except ValueError, exp: - raise ValueError('Bad float/double attribute (confidence): %s' % exp) - value = find_attr_value_('from', node) - if value is not None and 'from' not in already_processed: - already_processed.append('from') - try: - self.fromxx = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.fromxx < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - value = find_attr_value_('id', node) - if value is not None and 'id' not in already_processed: - already_processed.append('id') - self.id = value - self.id = ' '.join(self.id.split()) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class ProteinDomain - - -class Events(GeneratedsSuper): - """Events at the root node of a clade (e.g. one gene duplication).""" - subclass = None - superclass = None - def __init__(self, type_=None, duplications=None, speciations=None, losses=None, confidence=None, valueOf_=None): - self.type_ = type_ - self.duplications = duplications - self.speciations = speciations - self.losses = losses - self.confidence = confidence - def factory(*args_, **kwargs_): - if Events.subclass: - return Events.subclass(*args_, **kwargs_) - else: - return Events(*args_, **kwargs_) - factory = staticmethod(factory) - def get_type(self): return self.type_ - def set_type(self, type_): self.type_ = type_ - def validate_EventType(self, value): - # Validate type EventType, a restriction on xs:token. - pass - def get_duplications(self): return self.duplications - def set_duplications(self, duplications): self.duplications = duplications - def get_speciations(self): return self.speciations - def set_speciations(self, speciations): self.speciations = speciations - def get_losses(self): return self.losses - def set_losses(self, losses): self.losses = losses - def get_confidence(self): return self.confidence - def set_confidence(self, confidence): self.confidence = confidence - def export(self, outfile, level, namespace_='phy:', name_='Events', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Events') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Events'): - pass - def exportChildren(self, outfile, level, namespace_='phy:', name_='Events', fromsubclass_=False): - if self.type_ is not None: - showIndent(outfile, level) - outfile.write('<%stype>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.type_).encode(ExternalEncoding), input_name='type'), namespace_)) - if self.duplications is not None: - showIndent(outfile, level) - outfile.write('<%sduplications>%s\n' % (namespace_, self.gds_format_integer(self.duplications, input_name='duplications'), namespace_)) - if self.speciations is not None: - showIndent(outfile, level) - outfile.write('<%sspeciations>%s\n' % (namespace_, self.gds_format_integer(self.speciations, input_name='speciations'), namespace_)) - if self.losses is not None: - showIndent(outfile, level) - outfile.write('<%slosses>%s\n' % (namespace_, self.gds_format_integer(self.losses, input_name='losses'), namespace_)) - if self.confidence: - self.confidence.export(outfile, level, namespace_, name_='confidence') - def hasContent_(self): - if ( - self.type_ is not None or - self.duplications is not None or - self.speciations is not None or - self.losses is not None or - self.confidence is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Events'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - pass - def exportLiteralChildren(self, outfile, level, name_): - if self.type_ is not None: - showIndent(outfile, level) - outfile.write('type_=%s,\n' % quote_python(self.type_).encode(ExternalEncoding)) - if self.duplications is not None: - showIndent(outfile, level) - outfile.write('duplications=%d,\n' % self.duplications) - if self.speciations is not None: - showIndent(outfile, level) - outfile.write('speciations=%d,\n' % self.speciations) - if self.losses is not None: - showIndent(outfile, level) - outfile.write('losses=%d,\n' % self.losses) - if self.confidence is not None: - showIndent(outfile, level) - outfile.write('confidence=model_.Confidence(\n') - self.confidence.exportLiteral(outfile, level, name_='confidence') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'type': - type_ = child_.text - type_ = re_.sub(STRING_CLEANUP_PAT, " ", type_).strip() - type_ = self.gds_validate_string(type_, node, 'type') - self.type_ = type_ - self.validate_EventType(self.type_) # validate type EventType - elif nodeName_ == 'duplications': - sval_ = child_.text - try: - ival_ = int(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires integer: %s' % exp) - if ival_ < 0: - raise_parse_error(child_, 'requires nonNegativeInteger') - ival_ = self.gds_validate_integer(ival_, node, 'duplications') - self.duplications = ival_ - elif nodeName_ == 'speciations': - sval_ = child_.text - try: - ival_ = int(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires integer: %s' % exp) - if ival_ < 0: - raise_parse_error(child_, 'requires nonNegativeInteger') - ival_ = self.gds_validate_integer(ival_, node, 'speciations') - self.speciations = ival_ - elif nodeName_ == 'losses': - sval_ = child_.text - try: - ival_ = int(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires integer: %s' % exp) - if ival_ < 0: - raise_parse_error(child_, 'requires nonNegativeInteger') - ival_ = self.gds_validate_integer(ival_, node, 'losses') - self.losses = ival_ - elif nodeName_ == 'confidence': - obj_ = Confidence.factory() - obj_.build(child_) - self.set_confidence(obj_) -# end class Events - - -class BinaryCharacters(GeneratedsSuper): - """The names and/or counts of binary characters present, gained, and - lost at the root of a clade.""" - subclass = None - superclass = None - def __init__(self, lost_count=None, absent_count=None, present_count=None, type_=None, gained_count=None, gained=None, lost=None, present=None, absent=None, valueOf_=None): - self.lost_count = _cast(int, lost_count) - self.absent_count = _cast(int, absent_count) - self.present_count = _cast(int, present_count) - self.type_ = _cast(None, type_) - self.gained_count = _cast(int, gained_count) - self.gained = gained - self.lost = lost - self.present = present - self.absent = absent - def factory(*args_, **kwargs_): - if BinaryCharacters.subclass: - return BinaryCharacters.subclass(*args_, **kwargs_) - else: - return BinaryCharacters(*args_, **kwargs_) - factory = staticmethod(factory) - def get_gained(self): return self.gained - def set_gained(self, gained): self.gained = gained - def get_lost(self): return self.lost - def set_lost(self, lost): self.lost = lost - def get_present(self): return self.present - def set_present(self, present): self.present = present - def get_absent(self): return self.absent - def set_absent(self, absent): self.absent = absent - def get_lost_count(self): return self.lost_count - def set_lost_count(self, lost_count): self.lost_count = lost_count - def get_absent_count(self): return self.absent_count - def set_absent_count(self, absent_count): self.absent_count = absent_count - def get_present_count(self): return self.present_count - def set_present_count(self, present_count): self.present_count = present_count - def get_type(self): return self.type_ - def set_type(self, type_): self.type_ = type_ - def get_gained_count(self): return self.gained_count - def set_gained_count(self, gained_count): self.gained_count = gained_count - def export(self, outfile, level, namespace_='phy:', name_='BinaryCharacters', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='BinaryCharacters') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='BinaryCharacters'): - if self.lost_count is not None and 'lost_count' not in already_processed: - already_processed.append('lost_count') - outfile.write(' lost_count="%s"' % self.gds_format_integer(self.lost_count, input_name='lost_count')) - if self.absent_count is not None and 'absent_count' not in already_processed: - already_processed.append('absent_count') - outfile.write(' absent_count="%s"' % self.gds_format_integer(self.absent_count, input_name='absent_count')) - if self.present_count is not None and 'present_count' not in already_processed: - already_processed.append('present_count') - outfile.write(' present_count="%s"' % self.gds_format_integer(self.present_count, input_name='present_count')) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), )) - if self.gained_count is not None and 'gained_count' not in already_processed: - already_processed.append('gained_count') - outfile.write(' gained_count="%s"' % self.gds_format_integer(self.gained_count, input_name='gained_count')) - def exportChildren(self, outfile, level, namespace_='phy:', name_='BinaryCharacters', fromsubclass_=False): - if self.gained: - self.gained.export(outfile, level, namespace_, name_='gained') - if self.lost: - self.lost.export(outfile, level, namespace_, name_='lost') - if self.present: - self.present.export(outfile, level, namespace_, name_='present') - if self.absent: - self.absent.export(outfile, level, namespace_, name_='absent') - def hasContent_(self): - if ( - self.gained is not None or - self.lost is not None or - self.present is not None or - self.absent is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='BinaryCharacters'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.lost_count is not None and 'lost_count' not in already_processed: - already_processed.append('lost_count') - showIndent(outfile, level) - outfile.write('lost_count = %d,\n' % (self.lost_count,)) - if self.absent_count is not None and 'absent_count' not in already_processed: - already_processed.append('absent_count') - showIndent(outfile, level) - outfile.write('absent_count = %d,\n' % (self.absent_count,)) - if self.present_count is not None and 'present_count' not in already_processed: - already_processed.append('present_count') - showIndent(outfile, level) - outfile.write('present_count = %d,\n' % (self.present_count,)) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - showIndent(outfile, level) - outfile.write('type_ = "%s",\n' % (self.type_,)) - if self.gained_count is not None and 'gained_count' not in already_processed: - already_processed.append('gained_count') - showIndent(outfile, level) - outfile.write('gained_count = %d,\n' % (self.gained_count,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.gained is not None: - showIndent(outfile, level) - outfile.write('gained=model_.BinaryCharacterList(\n') - self.gained.exportLiteral(outfile, level, name_='gained') - showIndent(outfile, level) - outfile.write('),\n') - if self.lost is not None: - showIndent(outfile, level) - outfile.write('lost=model_.BinaryCharacterList(\n') - self.lost.exportLiteral(outfile, level, name_='lost') - showIndent(outfile, level) - outfile.write('),\n') - if self.present is not None: - showIndent(outfile, level) - outfile.write('present=model_.BinaryCharacterList(\n') - self.present.exportLiteral(outfile, level, name_='present') - showIndent(outfile, level) - outfile.write('),\n') - if self.absent is not None: - showIndent(outfile, level) - outfile.write('absent=model_.BinaryCharacterList(\n') - self.absent.exportLiteral(outfile, level, name_='absent') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('lost_count', node) - if value is not None and 'lost_count' not in already_processed: - already_processed.append('lost_count') - try: - self.lost_count = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.lost_count < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - value = find_attr_value_('absent_count', node) - if value is not None and 'absent_count' not in already_processed: - already_processed.append('absent_count') - try: - self.absent_count = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.absent_count < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - value = find_attr_value_('present_count', node) - if value is not None and 'present_count' not in already_processed: - already_processed.append('present_count') - try: - self.present_count = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.present_count < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - value = find_attr_value_('type', node) - if value is not None and 'type' not in already_processed: - already_processed.append('type') - self.type_ = value - self.type_ = ' '.join(self.type_.split()) - value = find_attr_value_('gained_count', node) - if value is not None and 'gained_count' not in already_processed: - already_processed.append('gained_count') - try: - self.gained_count = int(value) - except ValueError, exp: - raise_parse_error(node, 'Bad integer attribute: %s' % exp) - if self.gained_count < 0: - raise_parse_error(node, 'Invalid NonNegativeInteger') - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'gained': - obj_ = BinaryCharacterList.factory() - obj_.build(child_) - self.set_gained(obj_) - elif nodeName_ == 'lost': - obj_ = BinaryCharacterList.factory() - obj_.build(child_) - self.set_lost(obj_) - elif nodeName_ == 'present': - obj_ = BinaryCharacterList.factory() - obj_.build(child_) - self.set_present(obj_) - elif nodeName_ == 'absent': - obj_ = BinaryCharacterList.factory() - obj_.build(child_) - self.set_absent(obj_) -# end class BinaryCharacters - - -class BinaryCharacterList(GeneratedsSuper): - subclass = None - superclass = None - def __init__(self, bc=None, valueOf_=None): - if bc is None: - self.bc = [] - else: - self.bc = bc - def factory(*args_, **kwargs_): - if BinaryCharacterList.subclass: - return BinaryCharacterList.subclass(*args_, **kwargs_) - else: - return BinaryCharacterList(*args_, **kwargs_) - factory = staticmethod(factory) - def get_bc(self): return self.bc - def set_bc(self, bc): self.bc = bc - def add_bc(self, value): self.bc.append(value) - def insert_bc(self, index, value): self.bc[index] = value - def export(self, outfile, level, namespace_='phy:', name_='BinaryCharacterList', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='BinaryCharacterList') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='BinaryCharacterList'): - pass - def exportChildren(self, outfile, level, namespace_='phy:', name_='BinaryCharacterList', fromsubclass_=False): - for bc_ in self.bc: - showIndent(outfile, level) - outfile.write('<%sbc>%s\n' % (namespace_, self.gds_format_string(quote_xml(bc_).encode(ExternalEncoding), input_name='bc'), namespace_)) - def hasContent_(self): - if ( - self.bc - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='BinaryCharacterList'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - pass - def exportLiteralChildren(self, outfile, level, name_): - showIndent(outfile, level) - outfile.write('bc=[\n') - level += 1 - for bc_ in self.bc: - showIndent(outfile, level) - outfile.write('%s,\n' % quote_python(bc_).encode(ExternalEncoding)) - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'bc': - bc_ = child_.text - bc_ = re_.sub(STRING_CLEANUP_PAT, " ", bc_).strip() - bc_ = self.gds_validate_string(bc_, node, 'bc') - self.bc.append(bc_) -# end class BinaryCharacterList - - -class Reference(GeneratedsSuper): - """A literature reference for a clade. It is recommended to use the - 'doi' attribute instead of the free text 'desc' element whenever - possible.""" - subclass = None - superclass = None - def __init__(self, doi=None, desc=None, valueOf_=None): - self.doi = _cast(None, doi) - self.desc = desc - def factory(*args_, **kwargs_): - if Reference.subclass: - return Reference.subclass(*args_, **kwargs_) - else: - return Reference(*args_, **kwargs_) - factory = staticmethod(factory) - def get_desc(self): return self.desc - def set_desc(self, desc): self.desc = desc - def get_doi(self): return self.doi - def set_doi(self, doi): self.doi = doi - def export(self, outfile, level, namespace_='phy:', name_='Reference', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Reference') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Reference'): - if self.doi is not None and 'doi' not in already_processed: - already_processed.append('doi') - outfile.write(' doi=%s' % (quote_attrib(self.doi), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Reference', fromsubclass_=False): - if self.desc is not None: - showIndent(outfile, level) - outfile.write('<%sdesc>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.desc).encode(ExternalEncoding), input_name='desc'), namespace_)) - def hasContent_(self): - if ( - self.desc is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Reference'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.doi is not None and 'doi' not in already_processed: - already_processed.append('doi') - showIndent(outfile, level) - outfile.write('doi = %s,\n' % (self.doi,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.desc is not None: - showIndent(outfile, level) - outfile.write('desc=%s,\n' % quote_python(self.desc).encode(ExternalEncoding)) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('doi', node) - if value is not None and 'doi' not in already_processed: - already_processed.append('doi') - self.doi = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'desc': - desc_ = child_.text - desc_ = re_.sub(STRING_CLEANUP_PAT, " ", desc_).strip() - desc_ = self.gds_validate_string(desc_, node, 'desc') - self.desc = desc_ -# end class Reference - - -class Annotation(GeneratedsSuper): - """The annotation of a molecular sequence. It is recommended to - annotate by using the optional 'ref' attribute (some examples of - acceptable values for the ref attribute: 'GO:0008270', - 'KEGG:Tetrachloroethene degradation', 'EC:1.1.1.1'). Optional - element 'desc' allows for a free text description. Optional - element 'confidence' is used to state the type and value of - support for a annotation. Similarly, optional attribute - 'evidence' is used to describe the evidence for a annotation as - free text (e.g. 'experimental'). Optional element 'property' - allows for further, typed and referenced annotations from - external resources.""" - subclass = None - superclass = None - def __init__(self, source=None, type_=None, ref=None, evidence=None, desc=None, confidence=None, property=None, uri=None, valueOf_=None): - self.source = _cast(None, source) - self.type_ = _cast(None, type_) - self.ref = _cast(None, ref) - self.evidence = _cast(None, evidence) - self.desc = desc - self.confidence = confidence - if property is None: - self.property = [] - else: - self.property = property - self.uri = uri - def factory(*args_, **kwargs_): - if Annotation.subclass: - return Annotation.subclass(*args_, **kwargs_) - else: - return Annotation(*args_, **kwargs_) - factory = staticmethod(factory) - def get_desc(self): return self.desc - def set_desc(self, desc): self.desc = desc - def get_confidence(self): return self.confidence - def set_confidence(self, confidence): self.confidence = confidence - def get_property(self): return self.property - def set_property(self, property): self.property = property - def add_property(self, value): self.property.append(value) - def insert_property(self, index, value): self.property[index] = value - def get_uri(self): return self.uri - def set_uri(self, uri): self.uri = uri - def get_source(self): return self.source - def set_source(self, source): self.source = source - def get_type(self): return self.type_ - def set_type(self, type_): self.type_ = type_ - def get_ref(self): return self.ref - def set_ref(self, ref): self.ref = ref - def get_evidence(self): return self.evidence - def set_evidence(self, evidence): self.evidence = evidence - def export(self, outfile, level, namespace_='phy:', name_='Annotation', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Annotation') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Annotation'): - if self.source is not None and 'source' not in already_processed: - already_processed.append('source') - outfile.write(' source=%s' % (self.gds_format_string(quote_attrib(self.source).encode(ExternalEncoding), input_name='source'), )) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), )) - if self.ref is not None and 'ref' not in already_processed: - already_processed.append('ref') - outfile.write(' ref=%s' % (quote_attrib(self.ref), )) - if self.evidence is not None and 'evidence' not in already_processed: - already_processed.append('evidence') - outfile.write(' evidence=%s' % (self.gds_format_string(quote_attrib(self.evidence).encode(ExternalEncoding), input_name='evidence'), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Annotation', fromsubclass_=False): - if self.desc is not None: - showIndent(outfile, level) - outfile.write('<%sdesc>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.desc).encode(ExternalEncoding), input_name='desc'), namespace_)) - if self.confidence: - self.confidence.export(outfile, level, namespace_, name_='confidence') - for property_ in self.property: - property_.export(outfile, level, namespace_, name_='property') - if self.uri: - self.uri.export(outfile, level, namespace_, name_='uri') - def hasContent_(self): - if ( - self.desc is not None or - self.confidence is not None or - self.property or - self.uri is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Annotation'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.source is not None and 'source' not in already_processed: - already_processed.append('source') - showIndent(outfile, level) - outfile.write('source = "%s",\n' % (self.source,)) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - showIndent(outfile, level) - outfile.write('type_ = "%s",\n' % (self.type_,)) - if self.ref is not None and 'ref' not in already_processed: - already_processed.append('ref') - showIndent(outfile, level) - outfile.write('ref = %s,\n' % (self.ref,)) - if self.evidence is not None and 'evidence' not in already_processed: - already_processed.append('evidence') - showIndent(outfile, level) - outfile.write('evidence = "%s",\n' % (self.evidence,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.desc is not None: - showIndent(outfile, level) - outfile.write('desc=%s,\n' % quote_python(self.desc).encode(ExternalEncoding)) - if self.confidence is not None: - showIndent(outfile, level) - outfile.write('confidence=model_.Confidence(\n') - self.confidence.exportLiteral(outfile, level, name_='confidence') - showIndent(outfile, level) - outfile.write('),\n') - showIndent(outfile, level) - outfile.write('property=[\n') - level += 1 - for property_ in self.property: - showIndent(outfile, level) - outfile.write('model_.Property(\n') - property_.exportLiteral(outfile, level, name_='Property') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - if self.uri is not None: - showIndent(outfile, level) - outfile.write('uri=model_.Uri(\n') - self.uri.exportLiteral(outfile, level, name_='uri') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('source', node) - if value is not None and 'source' not in already_processed: - already_processed.append('source') - self.source = value - self.source = ' '.join(self.source.split()) - value = find_attr_value_('type', node) - if value is not None and 'type' not in already_processed: - already_processed.append('type') - self.type_ = value - self.type_ = ' '.join(self.type_.split()) - value = find_attr_value_('ref', node) - if value is not None and 'ref' not in already_processed: - already_processed.append('ref') - self.ref = value - value = find_attr_value_('evidence', node) - if value is not None and 'evidence' not in already_processed: - already_processed.append('evidence') - self.evidence = value - self.evidence = ' '.join(self.evidence.split()) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'desc': - desc_ = child_.text - desc_ = re_.sub(STRING_CLEANUP_PAT, " ", desc_).strip() - desc_ = self.gds_validate_string(desc_, node, 'desc') - self.desc = desc_ - elif nodeName_ == 'confidence': - obj_ = Confidence.factory() - obj_.build(child_) - self.set_confidence(obj_) - elif nodeName_ == 'property': - obj_ = Property.factory() - obj_.build(child_) - self.property.append(obj_) - elif nodeName_ == 'uri': - obj_ = Uri.factory() - obj_.build(child_) - self.set_uri(obj_) -# end class Annotation - - -class Property(GeneratedsSuper): - """Property allows for typed and referenced properties from external - resources to be attached to 'Phylogeny', 'Clade', and - 'Annotation'. The value of a property is its mixed (free text) - content. Attribute 'datatype' indicates the type of a property - and is limited to xsd-datatypes (e.g. 'xsd:string', - 'xsd:boolean', 'xsd:integer', 'xsd:decimal', 'xsd:float', - 'xsd:double', 'xsd:date', 'xsd:anyURI'). Attribute 'applies_to' - indicates the item to which a property applies to (e.g. 'node' - for the parent node of a clade, 'parent_branch' for the parent - branch of a clade). Attribute 'id_ref' allows to attached a - property specifically to one element (on the xml-level). - Optional attribute 'unit' is used to indicate the unit of the - property. An example: 200 - """ - subclass = None - superclass = None - def __init__(self, datatype=None, id_ref=None, ref=None, applies_to=None, unit=None, valueOf_=None, mixedclass_=None, content_=None): - self.datatype = _cast(None, datatype) - self.id_ref = _cast(None, id_ref) - self.ref = _cast(None, ref) - self.applies_to = _cast(None, applies_to) - self.unit = _cast(None, unit) - self.valueOf_ = valueOf_ - if mixedclass_ is None: - self.mixedclass_ = MixedContainer - else: - self.mixedclass_ = mixedclass_ - if content_ is None: - self.content_ = [] - else: - self.content_ = content_ - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if Property.subclass: - return Property.subclass(*args_, **kwargs_) - else: - return Property(*args_, **kwargs_) - factory = staticmethod(factory) - def get_datatype(self): return self.datatype - def set_datatype(self, datatype): self.datatype = datatype - def get_id_ref(self): return self.id_ref - def set_id_ref(self, id_ref): self.id_ref = id_ref - def get_ref(self): return self.ref - def set_ref(self, ref): self.ref = ref - def get_applies_to(self): return self.applies_to - def set_applies_to(self, applies_to): self.applies_to = applies_to - def get_unit(self): return self.unit - def set_unit(self, unit): self.unit = unit - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def export(self, outfile, level, namespace_='phy:', name_='Property', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Property') - outfile.write('>') - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Property'): - if self.datatype is not None and 'datatype' not in already_processed: - already_processed.append('datatype') - outfile.write(' datatype=%s' % (quote_attrib(self.datatype), )) - if self.id_ref is not None and 'id_ref' not in already_processed: - already_processed.append('id_ref') - outfile.write(' id_ref=%s' % (quote_attrib(self.id_ref), )) - if self.ref is not None and 'ref' not in already_processed: - already_processed.append('ref') - outfile.write(' ref=%s' % (quote_attrib(self.ref), )) - if self.applies_to is not None and 'applies_to' not in already_processed: - already_processed.append('applies_to') - outfile.write(' applies_to=%s' % (quote_attrib(self.applies_to), )) - if self.unit is not None and 'unit' not in already_processed: - already_processed.append('unit') - outfile.write(' unit=%s' % (quote_attrib(self.unit), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Property', fromsubclass_=False): - pass - def hasContent_(self): - if ( - self.valueOf_ - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Property'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.datatype is not None and 'datatype' not in already_processed: - already_processed.append('datatype') - showIndent(outfile, level) - outfile.write('datatype = %s,\n' % (self.datatype,)) - if self.id_ref is not None and 'id_ref' not in already_processed: - already_processed.append('id_ref') - showIndent(outfile, level) - outfile.write('id_ref = %s,\n' % (self.id_ref,)) - if self.ref is not None and 'ref' not in already_processed: - already_processed.append('ref') - showIndent(outfile, level) - outfile.write('ref = %s,\n' % (self.ref,)) - if self.applies_to is not None and 'applies_to' not in already_processed: - already_processed.append('applies_to') - showIndent(outfile, level) - outfile.write('applies_to = %s,\n' % (self.applies_to,)) - if self.unit is not None and 'unit' not in already_processed: - already_processed.append('unit') - showIndent(outfile, level) - outfile.write('unit = %s,\n' % (self.unit,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - self.valueOf_ = get_all_text_(node) - if node.text is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', node.text) - self.content_.append(obj_) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('datatype', node) - if value is not None and 'datatype' not in already_processed: - already_processed.append('datatype') - self.datatype = value - value = find_attr_value_('id_ref', node) - if value is not None and 'id_ref' not in already_processed: - already_processed.append('id_ref') - self.id_ref = value - value = find_attr_value_('ref', node) - if value is not None and 'ref' not in already_processed: - already_processed.append('ref') - self.ref = value - value = find_attr_value_('applies_to', node) - if value is not None and 'applies_to' not in already_processed: - already_processed.append('applies_to') - self.applies_to = value - value = find_attr_value_('unit', node) - if value is not None and 'unit' not in already_processed: - already_processed.append('unit') - self.unit = value - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if not fromsubclass_ and child_.tail is not None: - obj_ = self.mixedclass_(MixedContainer.CategoryText, - MixedContainer.TypeNone, '', child_.tail) - self.content_.append(obj_) - pass -# end class Property - - -class Uri(GeneratedsSuper): - """A uniform resource identifier. In general, this is expected to be an - URL (for example, to link to an image on a website, in which - case the 'type' attribute might be 'image' and 'desc' might be - 'image of a California sea hare').""" - subclass = None - superclass = None - def __init__(self, type_=None, desc=None, valueOf_=None): - self.type_ = _cast(None, type_) - self.desc = _cast(None, desc) - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if Uri.subclass: - return Uri.subclass(*args_, **kwargs_) - else: - return Uri(*args_, **kwargs_) - factory = staticmethod(factory) - def get_type(self): return self.type_ - def set_type(self, type_): self.type_ = type_ - def get_desc(self): return self.desc - def set_desc(self, desc): self.desc = desc - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def export(self, outfile, level, namespace_='phy:', name_='Uri', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Uri') - if self.hasContent_(): - outfile.write('>') - outfile.write(str(self.valueOf_).encode(ExternalEncoding)) - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Uri'): - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), )) - if self.desc is not None and 'desc' not in already_processed: - already_processed.append('desc') - outfile.write(' desc=%s' % (self.gds_format_string(quote_attrib(self.desc).encode(ExternalEncoding), input_name='desc'), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Uri', fromsubclass_=False): - pass - def hasContent_(self): - if ( - self.valueOf_ - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Uri'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - showIndent(outfile, level) - outfile.write('type_ = "%s",\n' % (self.type_,)) - if self.desc is not None and 'desc' not in already_processed: - already_processed.append('desc') - showIndent(outfile, level) - outfile.write('desc = "%s",\n' % (self.desc,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - self.valueOf_ = get_all_text_(node) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('type', node) - if value is not None and 'type' not in already_processed: - already_processed.append('type') - self.type_ = value - self.type_ = ' '.join(self.type_.split()) - value = find_attr_value_('desc', node) - if value is not None and 'desc' not in already_processed: - already_processed.append('desc') - self.desc = value - self.desc = ' '.join(self.desc.split()) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class Uri - - -class Confidence(GeneratedsSuper): - """A general purpose confidence element. For example this can be used - to express the bootstrap support value of a clade (in which case - the 'type' attribute is 'bootstrap').""" - subclass = None - superclass = None - def __init__(self, type_=None, valueOf_=None): - self.type_ = _cast(None, type_) - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if Confidence.subclass: - return Confidence.subclass(*args_, **kwargs_) - else: - return Confidence(*args_, **kwargs_) - factory = staticmethod(factory) - def get_type(self): return self.type_ - def set_type(self, type_): self.type_ = type_ - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def export(self, outfile, level, namespace_='phy:', name_='Confidence', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Confidence') - if self.hasContent_(): - outfile.write('>') - outfile.write(str(self.valueOf_).encode(ExternalEncoding)) - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Confidence'): - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Confidence', fromsubclass_=False): - pass - def hasContent_(self): - if ( - self.valueOf_ - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Confidence'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - showIndent(outfile, level) - outfile.write('type_ = "%s",\n' % (self.type_,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - self.valueOf_ = get_all_text_(node) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('type', node) - if value is not None and 'type' not in already_processed: - already_processed.append('type') - self.type_ = value - self.type_ = ' '.join(self.type_.split()) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class Confidence - - -class Id(GeneratedsSuper): - """A general purpose identifier element. Allows to indicate the - provider (or authority) of an identifier.""" - subclass = None - superclass = None - def __init__(self, provider=None, valueOf_=None): - self.provider = _cast(None, provider) - self.valueOf_ = valueOf_ - def factory(*args_, **kwargs_): - if Id.subclass: - return Id.subclass(*args_, **kwargs_) - else: - return Id(*args_, **kwargs_) - factory = staticmethod(factory) - def get_provider(self): return self.provider - def set_provider(self, provider): self.provider = provider - def get_valueOf_(self): return self.valueOf_ - def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def export(self, outfile, level, namespace_='phy:', name_='Id', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Id') - if self.hasContent_(): - outfile.write('>') - outfile.write(str(self.valueOf_).encode(ExternalEncoding)) - self.exportChildren(outfile, level + 1, namespace_, name_) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Id'): - if self.provider is not None and 'provider' not in already_processed: - already_processed.append('provider') - outfile.write(' provider=%s' % (self.gds_format_string(quote_attrib(self.provider).encode(ExternalEncoding), input_name='provider'), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Id', fromsubclass_=False): - pass - def hasContent_(self): - if ( - self.valueOf_ - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Id'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - showIndent(outfile, level) - outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,)) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.provider is not None and 'provider' not in already_processed: - already_processed.append('provider') - showIndent(outfile, level) - outfile.write('provider = "%s",\n' % (self.provider,)) - def exportLiteralChildren(self, outfile, level, name_): - pass - def build(self, node): - self.buildAttributes(node, node.attrib, []) - self.valueOf_ = get_all_text_(node) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('provider', node) - if value is not None and 'provider' not in already_processed: - already_processed.append('provider') - self.provider = value - self.provider = ' '.join(self.provider.split()) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - pass -# end class Id - - -class Distribution(GeneratedsSuper): - """The geographic distribution of the items of a clade (species, - sequences), intended for phylogeographic applications. The - location can be described either by free text in the 'desc' - element and/or by the coordinates of one or more 'Points' - (similar to the 'Point' element in Google's KML format) or by - 'Polygons'.""" - subclass = None - superclass = None - def __init__(self, desc=None, point=None, polygon=None, valueOf_=None): - self.desc = desc - if point is None: - self.point = [] - else: - self.point = point - if polygon is None: - self.polygon = [] - else: - self.polygon = polygon - def factory(*args_, **kwargs_): - if Distribution.subclass: - return Distribution.subclass(*args_, **kwargs_) - else: - return Distribution(*args_, **kwargs_) - factory = staticmethod(factory) - def get_desc(self): return self.desc - def set_desc(self, desc): self.desc = desc - def get_point(self): return self.point - def set_point(self, point): self.point = point - def add_point(self, value): self.point.append(value) - def insert_point(self, index, value): self.point[index] = value - def get_polygon(self): return self.polygon - def set_polygon(self, polygon): self.polygon = polygon - def add_polygon(self, value): self.polygon.append(value) - def insert_polygon(self, index, value): self.polygon[index] = value - def export(self, outfile, level, namespace_='phy:', name_='Distribution', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Distribution') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Distribution'): - pass - def exportChildren(self, outfile, level, namespace_='phy:', name_='Distribution', fromsubclass_=False): - if self.desc is not None: - showIndent(outfile, level) - outfile.write('<%sdesc>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.desc).encode(ExternalEncoding), input_name='desc'), namespace_)) - for point_ in self.point: - point_.export(outfile, level, namespace_, name_='point') - for polygon_ in self.polygon: - polygon_.export(outfile, level, namespace_, name_='polygon') - def hasContent_(self): - if ( - self.desc is not None or - self.point or - self.polygon - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Distribution'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - pass - def exportLiteralChildren(self, outfile, level, name_): - if self.desc is not None: - showIndent(outfile, level) - outfile.write('desc=%s,\n' % quote_python(self.desc).encode(ExternalEncoding)) - showIndent(outfile, level) - outfile.write('point=[\n') - level += 1 - for point_ in self.point: - showIndent(outfile, level) - outfile.write('model_.Point(\n') - point_.exportLiteral(outfile, level, name_='Point') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - showIndent(outfile, level) - outfile.write('polygon=[\n') - level += 1 - for polygon_ in self.polygon: - showIndent(outfile, level) - outfile.write('model_.Polygon(\n') - polygon_.exportLiteral(outfile, level, name_='Polygon') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'desc': - desc_ = child_.text - desc_ = re_.sub(STRING_CLEANUP_PAT, " ", desc_).strip() - desc_ = self.gds_validate_string(desc_, node, 'desc') - self.desc = desc_ - elif nodeName_ == 'point': - obj_ = Point.factory() - obj_.build(child_) - self.point.append(obj_) - elif nodeName_ == 'polygon': - obj_ = Polygon.factory() - obj_.build(child_) - self.polygon.append(obj_) -# end class Distribution - - -class Point(GeneratedsSuper): - """The coordinates of a point with an optional altitude (used by - element 'Distribution'). Required attributes are the - 'geodetic_datum' used to indicate the geodetic datum (also - called 'map datum', for example Google's KML uses 'WGS84'). - Attribute 'alt_unit' is the unit for the altitude (e.g. - 'meter').""" - subclass = None - superclass = None - def __init__(self, geodetic_datum=None, alt_unit=None, lat=None, long=None, alt=None, valueOf_=None): - self.geodetic_datum = _cast(None, geodetic_datum) - self.alt_unit = _cast(None, alt_unit) - self.lat = lat - self.long = long - self.alt = alt - def factory(*args_, **kwargs_): - if Point.subclass: - return Point.subclass(*args_, **kwargs_) - else: - return Point(*args_, **kwargs_) - factory = staticmethod(factory) - def get_lat(self): return self.lat - def set_lat(self, lat): self.lat = lat - def get_long(self): return self.long - def set_long(self, long): self.long = long - def get_alt(self): return self.alt - def set_alt(self, alt): self.alt = alt - def get_geodetic_datum(self): return self.geodetic_datum - def set_geodetic_datum(self, geodetic_datum): self.geodetic_datum = geodetic_datum - def get_alt_unit(self): return self.alt_unit - def set_alt_unit(self, alt_unit): self.alt_unit = alt_unit - def export(self, outfile, level, namespace_='phy:', name_='Point', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Point') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Point'): - if self.geodetic_datum is not None and 'geodetic_datum' not in already_processed: - already_processed.append('geodetic_datum') - outfile.write(' geodetic_datum=%s' % (self.gds_format_string(quote_attrib(self.geodetic_datum).encode(ExternalEncoding), input_name='geodetic_datum'), )) - if self.alt_unit is not None and 'alt_unit' not in already_processed: - already_processed.append('alt_unit') - outfile.write(' alt_unit=%s' % (self.gds_format_string(quote_attrib(self.alt_unit).encode(ExternalEncoding), input_name='alt_unit'), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Point', fromsubclass_=False): - if self.lat is not None: - showIndent(outfile, level) - outfile.write('<%slat>%s\n' % (namespace_, self.gds_format_float(self.lat, input_name='lat'), namespace_)) - if self.long is not None: - showIndent(outfile, level) - outfile.write('<%slong>%s\n' % (namespace_, self.gds_format_float(self.long, input_name='long'), namespace_)) - if self.alt is not None: - showIndent(outfile, level) - outfile.write('<%salt>%s\n' % (namespace_, self.gds_format_float(self.alt, input_name='alt'), namespace_)) - def hasContent_(self): - if ( - self.lat is not None or - self.long is not None or - self.alt is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Point'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.geodetic_datum is not None and 'geodetic_datum' not in already_processed: - already_processed.append('geodetic_datum') - showIndent(outfile, level) - outfile.write('geodetic_datum = "%s",\n' % (self.geodetic_datum,)) - if self.alt_unit is not None and 'alt_unit' not in already_processed: - already_processed.append('alt_unit') - showIndent(outfile, level) - outfile.write('alt_unit = "%s",\n' % (self.alt_unit,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.lat is not None: - showIndent(outfile, level) - outfile.write('lat=%f,\n' % self.lat) - if self.long is not None: - showIndent(outfile, level) - outfile.write('long=%f,\n' % self.long) - if self.alt is not None: - showIndent(outfile, level) - outfile.write('alt=%f,\n' % self.alt) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('geodetic_datum', node) - if value is not None and 'geodetic_datum' not in already_processed: - already_processed.append('geodetic_datum') - self.geodetic_datum = value - self.geodetic_datum = ' '.join(self.geodetic_datum.split()) - value = find_attr_value_('alt_unit', node) - if value is not None and 'alt_unit' not in already_processed: - already_processed.append('alt_unit') - self.alt_unit = value - self.alt_unit = ' '.join(self.alt_unit.split()) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'lat': - sval_ = child_.text - try: - fval_ = float(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires float or double: %s' % exp) - fval_ = self.gds_validate_float(fval_, node, 'lat') - self.lat = fval_ - elif nodeName_ == 'long': - sval_ = child_.text - try: - fval_ = float(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires float or double: %s' % exp) - fval_ = self.gds_validate_float(fval_, node, 'long') - self.long = fval_ - elif nodeName_ == 'alt': - sval_ = child_.text - try: - fval_ = float(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires float or double: %s' % exp) - fval_ = self.gds_validate_float(fval_, node, 'alt') - self.alt = fval_ -# end class Point - - -class Polygon(GeneratedsSuper): - """A polygon defined by a list of 'Points' (used by element - 'Distribution').""" - subclass = None - superclass = None - def __init__(self, point=None, valueOf_=None): - if point is None: - self.point = [] - else: - self.point = point - def factory(*args_, **kwargs_): - if Polygon.subclass: - return Polygon.subclass(*args_, **kwargs_) - else: - return Polygon(*args_, **kwargs_) - factory = staticmethod(factory) - def get_point(self): return self.point - def set_point(self, point): self.point = point - def add_point(self, value): self.point.append(value) - def insert_point(self, index, value): self.point[index] = value - def export(self, outfile, level, namespace_='phy:', name_='Polygon', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Polygon') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Polygon'): - pass - def exportChildren(self, outfile, level, namespace_='phy:', name_='Polygon', fromsubclass_=False): - for point_ in self.point: - point_.export(outfile, level, namespace_, name_='point') - def hasContent_(self): - if ( - self.point - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Polygon'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - pass - def exportLiteralChildren(self, outfile, level, name_): - showIndent(outfile, level) - outfile.write('point=[\n') - level += 1 - for point_ in self.point: - showIndent(outfile, level) - outfile.write('model_.Point(\n') - point_.exportLiteral(outfile, level, name_='Point') - showIndent(outfile, level) - outfile.write('),\n') - level -= 1 - showIndent(outfile, level) - outfile.write('],\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'point': - obj_ = Point.factory() - obj_.build(child_) - self.point.append(obj_) -# end class Polygon - - -class Date(GeneratedsSuper): - """A date associated with a clade/node. Its value can be numerical by - using the 'value' element and/or free text with the 'desc' - element' (e.g. 'Silurian'). If a numerical value is used, it is - recommended to employ the 'unit' attribute to indicate the type - of the numerical value (e.g. 'mya' for 'million years ago'). The - elements 'minimum' and 'maximum' are used the indicate a - range/confidence interval""" - subclass = None - superclass = None - def __init__(self, unit=None, desc=None, value=None, minimum=None, maximum=None, valueOf_=None): - self.unit = _cast(None, unit) - self.desc = desc - self.value = value - self.minimum = minimum - self.maximum = maximum - def factory(*args_, **kwargs_): - if Date.subclass: - return Date.subclass(*args_, **kwargs_) - else: - return Date(*args_, **kwargs_) - factory = staticmethod(factory) - def get_desc(self): return self.desc - def set_desc(self, desc): self.desc = desc - def get_value(self): return self.value - def set_value(self, value): self.value = value - def get_minimum(self): return self.minimum - def set_minimum(self, minimum): self.minimum = minimum - def get_maximum(self): return self.maximum - def set_maximum(self, maximum): self.maximum = maximum - def get_unit(self): return self.unit - def set_unit(self, unit): self.unit = unit - def export(self, outfile, level, namespace_='phy:', name_='Date', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='Date') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='Date'): - if self.unit is not None and 'unit' not in already_processed: - already_processed.append('unit') - outfile.write(' unit=%s' % (self.gds_format_string(quote_attrib(self.unit).encode(ExternalEncoding), input_name='unit'), )) - def exportChildren(self, outfile, level, namespace_='phy:', name_='Date', fromsubclass_=False): - if self.desc is not None: - showIndent(outfile, level) - outfile.write('<%sdesc>%s\n' % (namespace_, self.gds_format_string(quote_xml(self.desc).encode(ExternalEncoding), input_name='desc'), namespace_)) - if self.value is not None: - showIndent(outfile, level) - outfile.write('<%svalue>%s\n' % (namespace_, self.gds_format_float(self.value, input_name='value'), namespace_)) - if self.minimum is not None: - showIndent(outfile, level) - outfile.write('<%sminimum>%s\n' % (namespace_, self.gds_format_float(self.minimum, input_name='minimum'), namespace_)) - if self.maximum is not None: - showIndent(outfile, level) - outfile.write('<%smaximum>%s\n' % (namespace_, self.gds_format_float(self.maximum, input_name='maximum'), namespace_)) - def hasContent_(self): - if ( - self.desc is not None or - self.value is not None or - self.minimum is not None or - self.maximum is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='Date'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.unit is not None and 'unit' not in already_processed: - already_processed.append('unit') - showIndent(outfile, level) - outfile.write('unit = "%s",\n' % (self.unit,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.desc is not None: - showIndent(outfile, level) - outfile.write('desc=%s,\n' % quote_python(self.desc).encode(ExternalEncoding)) - if self.value is not None: - showIndent(outfile, level) - outfile.write('value=%f,\n' % self.value) - if self.minimum is not None: - showIndent(outfile, level) - outfile.write('minimum=%f,\n' % self.minimum) - if self.maximum is not None: - showIndent(outfile, level) - outfile.write('maximum=%f,\n' % self.maximum) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('unit', node) - if value is not None and 'unit' not in already_processed: - already_processed.append('unit') - self.unit = value - self.unit = ' '.join(self.unit.split()) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'desc': - desc_ = child_.text - desc_ = re_.sub(STRING_CLEANUP_PAT, " ", desc_).strip() - desc_ = self.gds_validate_string(desc_, node, 'desc') - self.desc = desc_ - elif nodeName_ == 'value': - sval_ = child_.text - try: - fval_ = float(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires float or double: %s' % exp) - fval_ = self.gds_validate_float(fval_, node, 'value') - self.value = fval_ - elif nodeName_ == 'minimum': - sval_ = child_.text - try: - fval_ = float(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires float or double: %s' % exp) - fval_ = self.gds_validate_float(fval_, node, 'minimum') - self.minimum = fval_ - elif nodeName_ == 'maximum': - sval_ = child_.text - try: - fval_ = float(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires float or double: %s' % exp) - fval_ = self.gds_validate_float(fval_, node, 'maximum') - self.maximum = fval_ -# end class Date - - -class BranchColor(GeneratedsSuper): - """This indicates the color of a clade when rendered (the color applies - to the whole clade unless overwritten by the color(s) of sub - clades).""" - subclass = None - superclass = None - def __init__(self, red=None, green=None, blue=None, valueOf_=None): - self.red = red - self.green = green - self.blue = blue - def factory(*args_, **kwargs_): - if BranchColor.subclass: - return BranchColor.subclass(*args_, **kwargs_) - else: - return BranchColor(*args_, **kwargs_) - factory = staticmethod(factory) - def get_red(self): return self.red - def set_red(self, red): self.red = red - def get_green(self): return self.green - def set_green(self, green): self.green = green - def get_blue(self): return self.blue - def set_blue(self, blue): self.blue = blue - def export(self, outfile, level, namespace_='phy:', name_='BranchColor', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='BranchColor') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='BranchColor'): - pass - def exportChildren(self, outfile, level, namespace_='phy:', name_='BranchColor', fromsubclass_=False): - if self.red is not None: - showIndent(outfile, level) - outfile.write('<%sred>%s\n' % (namespace_, self.gds_format_integer(self.red, input_name='red'), namespace_)) - if self.green is not None: - showIndent(outfile, level) - outfile.write('<%sgreen>%s\n' % (namespace_, self.gds_format_integer(self.green, input_name='green'), namespace_)) - if self.blue is not None: - showIndent(outfile, level) - outfile.write('<%sblue>%s\n' % (namespace_, self.gds_format_integer(self.blue, input_name='blue'), namespace_)) - def hasContent_(self): - if ( - self.red is not None or - self.green is not None or - self.blue is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='BranchColor'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - pass - def exportLiteralChildren(self, outfile, level, name_): - if self.red is not None: - showIndent(outfile, level) - outfile.write('red=%d,\n' % self.red) - if self.green is not None: - showIndent(outfile, level) - outfile.write('green=%d,\n' % self.green) - if self.blue is not None: - showIndent(outfile, level) - outfile.write('blue=%d,\n' % self.blue) - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - pass - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'red': - sval_ = child_.text - try: - ival_ = int(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires integer: %s' % exp) - ival_ = self.gds_validate_integer(ival_, node, 'red') - self.red = ival_ - elif nodeName_ == 'green': - sval_ = child_.text - try: - ival_ = int(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires integer: %s' % exp) - ival_ = self.gds_validate_integer(ival_, node, 'green') - self.green = ival_ - elif nodeName_ == 'blue': - sval_ = child_.text - try: - ival_ = int(sval_) - except (TypeError, ValueError), exp: - raise_parse_error(child_, 'requires integer: %s' % exp) - ival_ = self.gds_validate_integer(ival_, node, 'blue') - self.blue = ival_ -# end class BranchColor - - -class SequenceRelation(GeneratedsSuper): - """This is used to express a typed relationship between two sequences. - For example it could be used to describe an orthology (in which - case attribute 'type' is 'orthology').""" - subclass = None - superclass = None - def __init__(self, id_ref_0=None, id_ref_1=None, type_=None, distance=None, confidence=None, valueOf_=None): - self.id_ref_0 = _cast(None, id_ref_0) - self.id_ref_1 = _cast(None, id_ref_1) - self.type_ = _cast(None, type_) - self.distance = _cast(float, distance) - self.confidence = confidence - def factory(*args_, **kwargs_): - if SequenceRelation.subclass: - return SequenceRelation.subclass(*args_, **kwargs_) - else: - return SequenceRelation(*args_, **kwargs_) - factory = staticmethod(factory) - def get_confidence(self): return self.confidence - def set_confidence(self, confidence): self.confidence = confidence - def get_id_ref_0(self): return self.id_ref_0 - def set_id_ref_0(self, id_ref_0): self.id_ref_0 = id_ref_0 - def get_id_ref_1(self): return self.id_ref_1 - def set_id_ref_1(self, id_ref_1): self.id_ref_1 = id_ref_1 - def get_type(self): return self.type_ - def set_type(self, type_): self.type_ = type_ - def get_distance(self): return self.distance - def set_distance(self, distance): self.distance = distance - def export(self, outfile, level, namespace_='phy:', name_='SequenceRelation', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='SequenceRelation') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='SequenceRelation'): - if self.id_ref_0 is not None and 'id_ref_0' not in already_processed: - already_processed.append('id_ref_0') - outfile.write(' id_ref_0=%s' % (quote_attrib(self.id_ref_0), )) - if self.id_ref_1 is not None and 'id_ref_1' not in already_processed: - already_processed.append('id_ref_1') - outfile.write(' id_ref_1=%s' % (quote_attrib(self.id_ref_1), )) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - outfile.write(' type=%s' % (quote_attrib(self.type_), )) - if self.distance is not None and 'distance' not in already_processed: - already_processed.append('distance') - outfile.write(' distance="%s"' % self.gds_format_double(self.distance, input_name='distance')) - def exportChildren(self, outfile, level, namespace_='phy:', name_='SequenceRelation', fromsubclass_=False): - if self.confidence: - self.confidence.export(outfile, level, namespace_, name_='confidence') - def hasContent_(self): - if ( - self.confidence is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='SequenceRelation'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.id_ref_0 is not None and 'id_ref_0' not in already_processed: - already_processed.append('id_ref_0') - showIndent(outfile, level) - outfile.write('id_ref_0 = %s,\n' % (self.id_ref_0,)) - if self.id_ref_1 is not None and 'id_ref_1' not in already_processed: - already_processed.append('id_ref_1') - showIndent(outfile, level) - outfile.write('id_ref_1 = %s,\n' % (self.id_ref_1,)) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - showIndent(outfile, level) - outfile.write('type_ = %s,\n' % (self.type_,)) - if self.distance is not None and 'distance' not in already_processed: - already_processed.append('distance') - showIndent(outfile, level) - outfile.write('distance = %e,\n' % (self.distance,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.confidence is not None: - showIndent(outfile, level) - outfile.write('confidence=model_.Confidence(\n') - self.confidence.exportLiteral(outfile, level, name_='confidence') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('id_ref_0', node) - if value is not None and 'id_ref_0' not in already_processed: - already_processed.append('id_ref_0') - self.id_ref_0 = value - value = find_attr_value_('id_ref_1', node) - if value is not None and 'id_ref_1' not in already_processed: - already_processed.append('id_ref_1') - self.id_ref_1 = value - value = find_attr_value_('type', node) - if value is not None and 'type' not in already_processed: - already_processed.append('type') - self.type_ = value - value = find_attr_value_('distance', node) - if value is not None and 'distance' not in already_processed: - already_processed.append('distance') - try: - self.distance = float(value) - except ValueError, exp: - raise ValueError('Bad float/double attribute (distance): %s' % exp) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'confidence': - obj_ = Confidence.factory() - obj_.build(child_) - self.set_confidence(obj_) -# end class SequenceRelation - - -class CladeRelation(GeneratedsSuper): - """This is used to express a typed relationship between two clades. For - example it could be used to describe multiple parents of a - clade.""" - subclass = None - superclass = None - def __init__(self, id_ref_0=None, id_ref_1=None, type_=None, distance=None, confidence=None, valueOf_=None): - self.id_ref_0 = _cast(None, id_ref_0) - self.id_ref_1 = _cast(None, id_ref_1) - self.type_ = _cast(None, type_) - self.distance = _cast(float, distance) - self.confidence = confidence - def factory(*args_, **kwargs_): - if CladeRelation.subclass: - return CladeRelation.subclass(*args_, **kwargs_) - else: - return CladeRelation(*args_, **kwargs_) - factory = staticmethod(factory) - def get_confidence(self): return self.confidence - def set_confidence(self, confidence): self.confidence = confidence - def get_id_ref_0(self): return self.id_ref_0 - def set_id_ref_0(self, id_ref_0): self.id_ref_0 = id_ref_0 - def get_id_ref_1(self): return self.id_ref_1 - def set_id_ref_1(self, id_ref_1): self.id_ref_1 = id_ref_1 - def get_type(self): return self.type_ - def set_type(self, type_): self.type_ = type_ - def get_distance(self): return self.distance - def set_distance(self, distance): self.distance = distance - def export(self, outfile, level, namespace_='phy:', name_='CladeRelation', namespacedef_=''): - showIndent(outfile, level) - outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', )) - already_processed = [] - self.exportAttributes(outfile, level, already_processed, namespace_, name_='CladeRelation') - if self.hasContent_(): - outfile.write('>\n') - self.exportChildren(outfile, level + 1, namespace_, name_) - showIndent(outfile, level) - outfile.write('\n' % (namespace_, name_)) - else: - outfile.write('/>\n') - def exportAttributes(self, outfile, level, already_processed, namespace_='phy:', name_='CladeRelation'): - if self.id_ref_0 is not None and 'id_ref_0' not in already_processed: - already_processed.append('id_ref_0') - outfile.write(' id_ref_0=%s' % (quote_attrib(self.id_ref_0), )) - if self.id_ref_1 is not None and 'id_ref_1' not in already_processed: - already_processed.append('id_ref_1') - outfile.write(' id_ref_1=%s' % (quote_attrib(self.id_ref_1), )) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), )) - if self.distance is not None and 'distance' not in already_processed: - already_processed.append('distance') - outfile.write(' distance="%s"' % self.gds_format_double(self.distance, input_name='distance')) - def exportChildren(self, outfile, level, namespace_='phy:', name_='CladeRelation', fromsubclass_=False): - if self.confidence: - self.confidence.export(outfile, level, namespace_, name_='confidence') - def hasContent_(self): - if ( - self.confidence is not None - ): - return True - else: - return False - def exportLiteral(self, outfile, level, name_='CladeRelation'): - level += 1 - self.exportLiteralAttributes(outfile, level, [], name_) - if self.hasContent_(): - self.exportLiteralChildren(outfile, level, name_) - def exportLiteralAttributes(self, outfile, level, already_processed, name_): - if self.id_ref_0 is not None and 'id_ref_0' not in already_processed: - already_processed.append('id_ref_0') - showIndent(outfile, level) - outfile.write('id_ref_0 = %s,\n' % (self.id_ref_0,)) - if self.id_ref_1 is not None and 'id_ref_1' not in already_processed: - already_processed.append('id_ref_1') - showIndent(outfile, level) - outfile.write('id_ref_1 = %s,\n' % (self.id_ref_1,)) - if self.type_ is not None and 'type_' not in already_processed: - already_processed.append('type_') - showIndent(outfile, level) - outfile.write('type_ = "%s",\n' % (self.type_,)) - if self.distance is not None and 'distance' not in already_processed: - already_processed.append('distance') - showIndent(outfile, level) - outfile.write('distance = %e,\n' % (self.distance,)) - def exportLiteralChildren(self, outfile, level, name_): - if self.confidence is not None: - showIndent(outfile, level) - outfile.write('confidence=model_.Confidence(\n') - self.confidence.exportLiteral(outfile, level, name_='confidence') - showIndent(outfile, level) - outfile.write('),\n') - def build(self, node): - self.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_) - def buildAttributes(self, node, attrs, already_processed): - value = find_attr_value_('id_ref_0', node) - if value is not None and 'id_ref_0' not in already_processed: - already_processed.append('id_ref_0') - self.id_ref_0 = value - value = find_attr_value_('id_ref_1', node) - if value is not None and 'id_ref_1' not in already_processed: - already_processed.append('id_ref_1') - self.id_ref_1 = value - value = find_attr_value_('type', node) - if value is not None and 'type' not in already_processed: - already_processed.append('type') - self.type_ = value - self.type_ = ' '.join(self.type_.split()) - value = find_attr_value_('distance', node) - if value is not None and 'distance' not in already_processed: - already_processed.append('distance') - try: - self.distance = float(value) - except ValueError, exp: - raise ValueError('Bad float/double attribute (distance): %s' % exp) - def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): - if nodeName_ == 'confidence': - obj_ = Confidence.factory() - obj_.build(child_) - self.set_confidence(obj_) -# end class CladeRelation - - -USAGE_TEXT = """ -Usage: python .py [ -s ] -""" - -def usage(): - print USAGE_TEXT - sys.exit(1) - - -def get_root_tag(node): - tag = Tag_pattern_.match(node.tag).groups()[-1] - rootClass = globals().get(tag) - return tag, rootClass - - -def parse(inFileName): - doc = parsexml_(inFileName) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'phyloxml' - rootClass = Phyloxml - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## sys.stdout.write('\n') -## rootObj.export(sys.stdout, 0, name_=rootTag, -## namespacedef_='xmlns:phy="http://www.phyloxml.org/1.10/phyloxml.xsd"') - return rootObj - - -def parseString(inString): - from StringIO import StringIO - doc = parsexml_(StringIO(inString)) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'phyloxml' - rootClass = Phyloxml - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## sys.stdout.write('\n') -## rootObj.export(sys.stdout, 0, name_="phyloxml", -## namespacedef_='xmlns:phy="http://www.phyloxml.org/1.10/phyloxml.xsd"') - return rootObj - - -def parseLiteral(inFileName): - doc = parsexml_(inFileName) - rootNode = doc.getroot() - rootTag, rootClass = get_root_tag(rootNode) - if rootClass is None: - rootTag = 'phyloxml' - rootClass = Phyloxml - rootObj = rootClass.factory() - rootObj.build(rootNode) - # Enable Python to collect the space used by the DOM. - doc = None -## sys.stdout.write('#from phyloxml import *\n\n') -## sys.stdout.write('import phyloxml as model_\n\n') -## sys.stdout.write('rootObj = model_.rootTag(\n') -## rootObj.exportLiteral(sys.stdout, 0, name_=rootTag) -## sys.stdout.write(')\n') - return rootObj - - -def main(): - args = sys.argv[1:] - if len(args) == 1: - parse(args[0]) - else: - usage() - - -if __name__ == '__main__': - #import pdb; pdb.set_trace() - main() - - -__all__ = [ - "Accession", - "Annotation", - "BinaryCharacterList", - "BinaryCharacters", - "BranchColor", - "Clade", - "CladeRelation", - "Confidence", - "Date", - "Distribution", - "DomainArchitecture", - "Events", - "Id", - "MolSeq", - "Phylogeny", - "Phyloxml", - "Point", - "Polygon", - "Property", - "ProteinDomain", - "Reference", - "Sequence", - "SequenceRelation", - "Taxonomy", - "Uri" - ] diff --git a/ete2/phyloxml/_phyloxml.pyc b/ete2/phyloxml/_phyloxml.pyc deleted file mode 100644 index 6621ffe..0000000 Binary files a/ete2/phyloxml/_phyloxml.pyc and /dev/null differ diff --git a/ete2/phyloxml/_phyloxml_tree.py b/ete2/phyloxml/_phyloxml_tree.py deleted file mode 100644 index 95b40de..0000000 --- a/ete2/phyloxml/_phyloxml_tree.py +++ /dev/null @@ -1,153 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -""" -This module implements the interoperability between Phylogeny and -Clade attributes in the phyloXMl schema and the ETE Tree objects. - -The PhyloxmlTree class should be use as a substitute for base Clade -and Phylogeny classes. - -""" - -import sys -from _phyloxml import Clade, Phylogeny, Confidence, Tag_pattern_ -from ete2 import PhyloTree - -class PhyloxmlTree(PhyloTree): - ''' PhyloTree object supporting phyloXML format. ''' - - def __repr__(self): - return "PhyloXML ETE tree <%s>" %hex(hash(self)) - - def _get_dist(self): - v = self.phyloxml_clade.get_branch_length_attr() - if v is None: - v = self.phyloxml_clade.get_branch_length() - if v is None: - self._set_dist(self._dist) - v = self.phyloxml_clade.get_branch_length_attr() - return float(v) - - def _set_dist(self, value): - try: - self.phyloxml_clade.set_branch_length(float(value)) - self.phyloxml_clade.set_branch_length_attr(float(value)) - except ValueError: - raise - - def _get_support(self): - if len(self.phyloxml_clade.confidence) == 0: - _c = Confidence(valueOf_=1.0, type_="branch_support") - self.phyloxml_clade.add_confidence(_c) - return float(self.phyloxml_clade.confidence[0].valueOf_) - - def _set_support(self, value): - self._get_support() - self.phyloxml_clade.confidence[0].valueOf_ = float(value) - - def _get_name(self): - return self.phyloxml_clade.get_name() - - def _set_name(self, value): - try: - self.phyloxml_clade.set_name(value) - except ValueError: - raise - - def _get_children(self): - return self.phyloxml_clade.clade - - dist = property(fget=_get_dist, fset=_set_dist) - support = property(fget=_get_support, fset=_set_support) - children = property(fget=_get_children) - name = property(fget=_get_name, fset=_set_name) - - def __init__(self, phyloxml_clade=None, phyloxml_phylogeny=None, **kargs): - if not phyloxml_phylogeny: - self.phyloxml_phylogeny = Phylogeny() - else: - self.phyloxml_phylogeny = phyloxml_phylogeny - if not phyloxml_clade: - self.phyloxml_clade = Clade() - self.phyloxml_clade.set_branch_length(0.0) - self.phyloxml_clade.set_name("NoName") - #self.__support = Confidence(valueOf_=1.0, type_="branch_support") - #self.phyloxml_clade.add_confidence(self.__support) - else: - self.phyloxml_clade = phyloxml_clade - super(PhyloxmlTree, self).__init__(**kargs) - - def build(self, node): - nodetype = Tag_pattern_.match(node.tag).groups()[-1] - if nodetype == 'phylogeny': - self.phyloxml_phylogeny.buildAttributes(node, node.attrib, []) - elif nodetype == 'clade': - if "branch_length" in node.attrib: - node.attrib["branch_length_attr"] = node.attrib["branch_length"] - self.phyloxml_clade.buildAttributes(node, node.attrib, []) - for child in node: - nodeName_ = Tag_pattern_.match(child.tag).groups()[-1] - self.buildChildren(child, node, nodeName_, nodetype=nodetype) - - def buildChildren(self, child_, node, nodeName_, fromsubclass=False, nodetype=None): - if nodetype == 'phylogeny': - baseclass = self.phyloxml_phylogeny - if nodeName_ == 'clade': - self.build(child_) - else: - baseclass.buildChildren(child_, node, nodeName_) - elif nodetype == 'clade': - baseclass = self.phyloxml_clade - if nodeName_ == 'clade': - new_node = self.add_child() - new_node.build(child_) - else: - baseclass.buildChildren(child_, node, nodeName_) - - def export(self, outfile=sys.stdout, level=0, namespace_='phy:', name_='Phylogeny', namespacedef_=''): - if not self.up: - self.phyloxml_phylogeny.clade = self.phyloxml_clade - self.phyloxml_clade.clade = self.children - self.phyloxml_phylogeny.export(outfile=outfile, level=level, name_=name_, namespacedef_=namespacedef_) - else: - self.phyloxml_clade.clade = self.children - self.phyloxml_clade.export(outfile=outfile, level=level, name_=name_, namespacedef_=namespacedef_) - diff --git a/ete2/phyloxml/_phyloxml_tree.pyc b/ete2/phyloxml/_phyloxml_tree.pyc deleted file mode 100644 index 1346cff..0000000 Binary files a/ete2/phyloxml/_phyloxml_tree.pyc and /dev/null differ diff --git a/ete2/treeview/__init__.py b/ete2/treeview/__init__.py deleted file mode 100644 index fd0e976..0000000 --- a/ete2/treeview/__init__.py +++ /dev/null @@ -1,45 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - - -from main import * -from faces import * -from svg_colors import * diff --git a/ete2/treeview/__init__.pyc b/ete2/treeview/__init__.pyc deleted file mode 100644 index 58a7fed..0000000 Binary files a/ete2/treeview/__init__.pyc and /dev/null differ diff --git a/ete2/treeview/_about.py b/ete2/treeview/_about.py deleted file mode 100644 index a75a09c..0000000 --- a/ete2/treeview/_about.py +++ /dev/null @@ -1,83 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- - -# Form implementation generated from reading ui file 'about.ui' -# -# Created: Tue Jan 10 15:56:58 2012 -# by: PyQt4 UI code generator 4.7.2 -# -# WARNING! All changes made in this file will be lost! - -from PyQt4 import QtCore, QtGui - -class Ui_About(object): - def setupUi(self, About): - About.setObjectName("About") - About.resize(462, 249) - self.verticalLayoutWidget = QtGui.QWidget(About) - self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 0, 441, 208)) - self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") - self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget) - self.verticalLayout.setObjectName("verticalLayout") - self.label = QtGui.QLabel(self.verticalLayoutWidget) - self.label.setObjectName("label") - self.verticalLayout.addWidget(self.label) - self.version = QtGui.QLabel(self.verticalLayoutWidget) - self.version.setObjectName("version") - self.verticalLayout.addWidget(self.version) - - self.retranslateUi(About) - QtCore.QMetaObject.connectSlotsByName(About) - - def retranslateUi(self, About): - About.setWindowTitle(QtGui.QApplication.translate("About", "Dialog", None, QtGui.QApplication.UnicodeUTF8)) - self.label.setText(QtGui.QApplication.translate("About", "\n" -"\n" -"

\n" -"

ETE: a python Environment for Tree Exploration

\n" -"

http://ete.cgenomics.org

\n" -"

", None, QtGui.QApplication.UnicodeUTF8)) - self.version.setText(QtGui.QApplication.translate("About", "VERSION", None, QtGui.QApplication.UnicodeUTF8)) - -import ete_resources_rc diff --git a/ete2/treeview/_about.pyc b/ete2/treeview/_about.pyc deleted file mode 100644 index a9d8810..0000000 Binary files a/ete2/treeview/_about.pyc and /dev/null differ diff --git a/ete2/treeview/_mainwindow.py b/ete2/treeview/_mainwindow.py deleted file mode 100644 index 7108a43..0000000 --- a/ete2/treeview/_mainwindow.py +++ /dev/null @@ -1,264 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- - -# Form implementation generated from reading ui file 'ete_qt4app.ui' -# -# Created: Tue Jan 10 15:56:57 2012 -# by: PyQt4 UI code generator 4.7.2 -# -# WARNING! All changes made in this file will be lost! - -from PyQt4 import QtCore, QtGui - -class Ui_MainWindow(object): - def setupUi(self, MainWindow): - MainWindow.setObjectName("MainWindow") - MainWindow.resize(673, 493) - self.centralwidget = QtGui.QWidget(MainWindow) - self.centralwidget.setObjectName("centralwidget") - MainWindow.setCentralWidget(self.centralwidget) - self.menubar = QtGui.QMenuBar(MainWindow) - self.menubar.setGeometry(QtCore.QRect(0, 0, 673, 27)) - self.menubar.setObjectName("menubar") - self.menuFile = QtGui.QMenu(self.menubar) - self.menuFile.setObjectName("menuFile") - self.menuAbout = QtGui.QMenu(self.menubar) - self.menuAbout.setObjectName("menuAbout") - MainWindow.setMenuBar(self.menubar) - self.statusbar = QtGui.QStatusBar(MainWindow) - self.statusbar.setObjectName("statusbar") - MainWindow.setStatusBar(self.statusbar) - self.toolBar = QtGui.QToolBar(MainWindow) - self.toolBar.setEnabled(True) - self.toolBar.setObjectName("toolBar") - MainWindow.addToolBar(QtCore.Qt.ToolBarArea(QtCore.Qt.TopToolBarArea), self.toolBar) - self.actionOpen = QtGui.QAction(MainWindow) - icon = QtGui.QIcon() - icon.addPixmap(QtGui.QPixmap(":/ete icons/fileopen.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionOpen.setIcon(icon) - font = QtGui.QFont() - self.actionOpen.setFont(font) - self.actionOpen.setObjectName("actionOpen") - self.actionPaste_newick = QtGui.QAction(MainWindow) - self.actionPaste_newick.setObjectName("actionPaste_newick") - self.actionSave_image = QtGui.QAction(MainWindow) - icon1 = QtGui.QIcon() - icon1.addPixmap(QtGui.QPixmap(":/ete icons/filesave.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionSave_image.setIcon(icon1) - self.actionSave_image.setObjectName("actionSave_image") - self.actionSave_region = QtGui.QAction(MainWindow) - self.actionSave_region.setObjectName("actionSave_region") - self.actionBranchLength = QtGui.QAction(MainWindow) - self.actionBranchLength.setCheckable(True) - icon2 = QtGui.QIcon() - icon2.addPixmap(QtGui.QPixmap(":/ete icons/show_dist.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionBranchLength.setIcon(icon2) - self.actionBranchLength.setObjectName("actionBranchLength") - self.actionZoomIn = QtGui.QAction(MainWindow) - icon3 = QtGui.QIcon() - icon3.addPixmap(QtGui.QPixmap(":/ete icons/zoom_in.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionZoomIn.setIcon(icon3) - self.actionZoomIn.setObjectName("actionZoomIn") - self.actionZoomOut = QtGui.QAction(MainWindow) - icon4 = QtGui.QIcon() - icon4.addPixmap(QtGui.QPixmap(":/ete icons/zoom_out.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionZoomOut.setIcon(icon4) - self.actionZoomOut.setObjectName("actionZoomOut") - self.actionETE = QtGui.QAction(MainWindow) - self.actionETE.setObjectName("actionETE") - self.actionForceTopology = QtGui.QAction(MainWindow) - self.actionForceTopology.setCheckable(True) - icon5 = QtGui.QIcon() - icon5.addPixmap(QtGui.QPixmap(":/ete icons/force_topo.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionForceTopology.setIcon(icon5) - self.actionForceTopology.setProperty("HOLA", False) - self.actionForceTopology.setObjectName("actionForceTopology") - self.actionSave_newick = QtGui.QAction(MainWindow) - self.actionSave_newick.setIcon(icon1) - self.actionSave_newick.setObjectName("actionSave_newick") - self.actionZoomInX = QtGui.QAction(MainWindow) - icon6 = QtGui.QIcon() - icon6.addPixmap(QtGui.QPixmap(":/ete icons/x_expand.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionZoomInX.setIcon(icon6) - self.actionZoomInX.setObjectName("actionZoomInX") - self.actionZoomOutX = QtGui.QAction(MainWindow) - icon7 = QtGui.QIcon() - icon7.addPixmap(QtGui.QPixmap(":/ete icons/x_reduce.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionZoomOutX.setIcon(icon7) - self.actionZoomOutX.setObjectName("actionZoomOutX") - self.actionZoomInY = QtGui.QAction(MainWindow) - icon8 = QtGui.QIcon() - icon8.addPixmap(QtGui.QPixmap(":/ete icons/y_expand.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionZoomInY.setIcon(icon8) - self.actionZoomInY.setObjectName("actionZoomInY") - self.actionZoomOutY = QtGui.QAction(MainWindow) - icon9 = QtGui.QIcon() - icon9.addPixmap(QtGui.QPixmap(":/ete icons/y_reduce.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionZoomOutY.setIcon(icon9) - self.actionZoomOutY.setProperty("actionBranchSupport", False) - self.actionZoomOutY.setObjectName("actionZoomOutY") - self.actionFit2tree = QtGui.QAction(MainWindow) - icon10 = QtGui.QIcon() - icon10.addPixmap(QtGui.QPixmap(":/ete icons/fit_tree.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionFit2tree.setIcon(icon10) - self.actionFit2tree.setObjectName("actionFit2tree") - self.actionFit2region = QtGui.QAction(MainWindow) - icon11 = QtGui.QIcon() - icon11.addPixmap(QtGui.QPixmap(":/ete icons/fit_region.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionFit2region.setIcon(icon11) - self.actionFit2region.setObjectName("actionFit2region") - self.actionRenderPDF = QtGui.QAction(MainWindow) - icon12 = QtGui.QIcon() - icon12.addPixmap(QtGui.QPixmap(":/ete icons/export_pdf.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionRenderPDF.setIcon(icon12) - self.actionRenderPDF.setObjectName("actionRenderPDF") - self.actionSearchNode = QtGui.QAction(MainWindow) - icon13 = QtGui.QIcon() - icon13.addPixmap(QtGui.QPixmap(":/ete icons/search.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionSearchNode.setIcon(icon13) - self.actionSearchNode.setObjectName("actionSearchNode") - self.actionClear_search = QtGui.QAction(MainWindow) - icon14 = QtGui.QIcon() - icon14.addPixmap(QtGui.QPixmap(":/ete icons/clean_search.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionClear_search.setIcon(icon14) - self.actionClear_search.setObjectName("actionClear_search") - self.actionShow_newick = QtGui.QAction(MainWindow) - icon15 = QtGui.QIcon() - icon15.addPixmap(QtGui.QPixmap(":/ete icons/show_newick.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionShow_newick.setIcon(icon15) - self.actionShow_newick.setObjectName("actionShow_newick") - self.actionShow_node_attributes_box = QtGui.QAction(MainWindow) - self.actionShow_node_attributes_box.setCheckable(True) - self.actionShow_node_attributes_box.setChecked(True) - self.actionShow_node_attributes_box.setObjectName("actionShow_node_attributes_box") - self.actionRender_selected_region = QtGui.QAction(MainWindow) - self.actionRender_selected_region.setIcon(icon12) - self.actionRender_selected_region.setShortcutContext(QtCore.Qt.WidgetShortcut) - self.actionRender_selected_region.setObjectName("actionRender_selected_region") - self.actionBranchSupport = QtGui.QAction(MainWindow) - self.actionBranchSupport.setCheckable(True) - icon16 = QtGui.QIcon() - icon16.addPixmap(QtGui.QPixmap(":/ete icons/show_support.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionBranchSupport.setIcon(icon16) - self.actionBranchSupport.setObjectName("actionBranchSupport") - self.actionLeafName = QtGui.QAction(MainWindow) - self.actionLeafName.setCheckable(True) - icon17 = QtGui.QIcon() - icon17.addPixmap(QtGui.QPixmap(":/ete icons/show_names.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) - self.actionLeafName.setIcon(icon17) - self.actionLeafName.setObjectName("actionLeafName") - self.menuFile.addAction(self.actionOpen) - self.menuFile.addAction(self.actionPaste_newick) - self.menuFile.addAction(self.actionSave_newick) - self.menuFile.addAction(self.actionRenderPDF) - self.menuFile.addAction(self.actionRender_selected_region) - self.menuAbout.addAction(self.actionETE) - self.menubar.addAction(self.menuFile.menuAction()) - self.menubar.addAction(self.menuAbout.menuAction()) - self.toolBar.addAction(self.actionZoomIn) - self.toolBar.addAction(self.actionZoomOut) - self.toolBar.addAction(self.actionFit2tree) - self.toolBar.addAction(self.actionFit2region) - self.toolBar.addAction(self.actionZoomInX) - self.toolBar.addAction(self.actionZoomOutX) - self.toolBar.addAction(self.actionZoomInY) - self.toolBar.addAction(self.actionZoomOutY) - self.toolBar.addAction(self.actionSearchNode) - self.toolBar.addAction(self.actionClear_search) - self.toolBar.addAction(self.actionForceTopology) - self.toolBar.addAction(self.actionBranchLength) - self.toolBar.addAction(self.actionBranchSupport) - self.toolBar.addAction(self.actionLeafName) - self.toolBar.addAction(self.actionRenderPDF) - self.toolBar.addAction(self.actionShow_newick) - - self.retranslateUi(MainWindow) - QtCore.QMetaObject.connectSlotsByName(MainWindow) - - def retranslateUi(self, MainWindow): - MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) - self.menuFile.setTitle(QtGui.QApplication.translate("MainWindow", "File", None, QtGui.QApplication.UnicodeUTF8)) - self.menuAbout.setTitle(QtGui.QApplication.translate("MainWindow", "About", None, QtGui.QApplication.UnicodeUTF8)) - self.toolBar.setWindowTitle(QtGui.QApplication.translate("MainWindow", "toolBar", None, QtGui.QApplication.UnicodeUTF8)) - self.actionOpen.setText(QtGui.QApplication.translate("MainWindow", "Open newick tree", None, QtGui.QApplication.UnicodeUTF8)) - self.actionOpen.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+O", None, QtGui.QApplication.UnicodeUTF8)) - self.actionPaste_newick.setText(QtGui.QApplication.translate("MainWindow", "Paste newick", None, QtGui.QApplication.UnicodeUTF8)) - self.actionPaste_newick.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+P", None, QtGui.QApplication.UnicodeUTF8)) - self.actionSave_image.setText(QtGui.QApplication.translate("MainWindow", "Save Image", None, QtGui.QApplication.UnicodeUTF8)) - self.actionSave_region.setText(QtGui.QApplication.translate("MainWindow", "Save region", None, QtGui.QApplication.UnicodeUTF8)) - self.actionSave_region.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+A", None, QtGui.QApplication.UnicodeUTF8)) - self.actionBranchLength.setText(QtGui.QApplication.translate("MainWindow", "Show branch info", None, QtGui.QApplication.UnicodeUTF8)) - self.actionBranchLength.setShortcut(QtGui.QApplication.translate("MainWindow", "L", None, QtGui.QApplication.UnicodeUTF8)) - self.actionZoomIn.setText(QtGui.QApplication.translate("MainWindow", "Zoom in", None, QtGui.QApplication.UnicodeUTF8)) - self.actionZoomIn.setShortcut(QtGui.QApplication.translate("MainWindow", "Z", None, QtGui.QApplication.UnicodeUTF8)) - self.actionZoomOut.setText(QtGui.QApplication.translate("MainWindow", "Zoom out", None, QtGui.QApplication.UnicodeUTF8)) - self.actionZoomOut.setShortcut(QtGui.QApplication.translate("MainWindow", "X", None, QtGui.QApplication.UnicodeUTF8)) - self.actionETE.setText(QtGui.QApplication.translate("MainWindow", "ETE", None, QtGui.QApplication.UnicodeUTF8)) - self.actionForceTopology.setText(QtGui.QApplication.translate("MainWindow", "Force topology", None, QtGui.QApplication.UnicodeUTF8)) - self.actionForceTopology.setToolTip(QtGui.QApplication.translate("MainWindow", "Allows to see topology by setting assuming all branch lenghts are 1.0", None, QtGui.QApplication.UnicodeUTF8)) - self.actionForceTopology.setShortcut(QtGui.QApplication.translate("MainWindow", "T", None, QtGui.QApplication.UnicodeUTF8)) - self.actionSave_newick.setText(QtGui.QApplication.translate("MainWindow", "Save as newick", None, QtGui.QApplication.UnicodeUTF8)) - self.actionZoomInX.setText(QtGui.QApplication.translate("MainWindow", "Increase X scale", None, QtGui.QApplication.UnicodeUTF8)) - self.actionZoomOutX.setText(QtGui.QApplication.translate("MainWindow", "Decrease X scale", None, QtGui.QApplication.UnicodeUTF8)) - self.actionZoomInY.setText(QtGui.QApplication.translate("MainWindow", "Increase Y scale", None, QtGui.QApplication.UnicodeUTF8)) - self.actionZoomOutY.setText(QtGui.QApplication.translate("MainWindow", "Decrease Y scale", None, QtGui.QApplication.UnicodeUTF8)) - self.actionFit2tree.setText(QtGui.QApplication.translate("MainWindow", "Fit to tree", None, QtGui.QApplication.UnicodeUTF8)) - self.actionFit2tree.setShortcut(QtGui.QApplication.translate("MainWindow", "W", None, QtGui.QApplication.UnicodeUTF8)) - self.actionFit2region.setText(QtGui.QApplication.translate("MainWindow", "Fit to selection", None, QtGui.QApplication.UnicodeUTF8)) - self.actionFit2region.setShortcut(QtGui.QApplication.translate("MainWindow", "R", None, QtGui.QApplication.UnicodeUTF8)) - self.actionRenderPDF.setText(QtGui.QApplication.translate("MainWindow", "Render PDF image", None, QtGui.QApplication.UnicodeUTF8)) - self.actionSearchNode.setText(QtGui.QApplication.translate("MainWindow", "Search", None, QtGui.QApplication.UnicodeUTF8)) - self.actionSearchNode.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+S", None, QtGui.QApplication.UnicodeUTF8)) - self.actionClear_search.setText(QtGui.QApplication.translate("MainWindow", "Clear search", None, QtGui.QApplication.UnicodeUTF8)) - self.actionClear_search.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+C", None, QtGui.QApplication.UnicodeUTF8)) - self.actionShow_newick.setText(QtGui.QApplication.translate("MainWindow", "Show newick", None, QtGui.QApplication.UnicodeUTF8)) - self.actionShow_newick.setShortcut(QtGui.QApplication.translate("MainWindow", "N", None, QtGui.QApplication.UnicodeUTF8)) - self.actionShow_node_attributes_box.setText(QtGui.QApplication.translate("MainWindow", "Show node attributes box", None, QtGui.QApplication.UnicodeUTF8)) - self.actionRender_selected_region.setText(QtGui.QApplication.translate("MainWindow", "Render selected region", None, QtGui.QApplication.UnicodeUTF8)) - self.actionBranchSupport.setText(QtGui.QApplication.translate("MainWindow", "Show branch support", None, QtGui.QApplication.UnicodeUTF8)) - self.actionBranchSupport.setToolTip(QtGui.QApplication.translate("MainWindow", "Show branch support", None, QtGui.QApplication.UnicodeUTF8)) - self.actionBranchSupport.setShortcut(QtGui.QApplication.translate("MainWindow", "S", None, QtGui.QApplication.UnicodeUTF8)) - self.actionLeafName.setText(QtGui.QApplication.translate("MainWindow", "Show leaf names", None, QtGui.QApplication.UnicodeUTF8)) - self.actionLeafName.setToolTip(QtGui.QApplication.translate("MainWindow", "show leaf names", None, QtGui.QApplication.UnicodeUTF8)) - self.actionLeafName.setShortcut(QtGui.QApplication.translate("MainWindow", "N", None, QtGui.QApplication.UnicodeUTF8)) - -import ete_resources_rc diff --git a/ete2/treeview/_mainwindow.pyc b/ete2/treeview/_mainwindow.pyc deleted file mode 100644 index 7ac4318..0000000 Binary files a/ete2/treeview/_mainwindow.pyc and /dev/null differ diff --git a/ete2/treeview/_open_newick.py b/ete2/treeview/_open_newick.py deleted file mode 100644 index f121536..0000000 --- a/ete2/treeview/_open_newick.py +++ /dev/null @@ -1,68 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- - -# Form implementation generated from reading ui file 'open_newick.ui' -# -# Created: Tue Jan 10 15:56:56 2012 -# by: PyQt4 UI code generator 4.7.2 -# -# WARNING! All changes made in this file will be lost! - -from PyQt4 import QtCore, QtGui - -class Ui_OpenNewick(object): - def setupUi(self, OpenNewick): - OpenNewick.setObjectName("OpenNewick") - OpenNewick.resize(569, 353) - self.comboBox = QtGui.QComboBox(OpenNewick) - self.comboBox.setGeometry(QtCore.QRect(460, 300, 81, 23)) - self.comboBox.setObjectName("comboBox") - self.widget = QtGui.QWidget(OpenNewick) - self.widget.setGeometry(QtCore.QRect(30, 10, 371, 321)) - self.widget.setObjectName("widget") - - self.retranslateUi(OpenNewick) - QtCore.QMetaObject.connectSlotsByName(OpenNewick) - - def retranslateUi(self, OpenNewick): - OpenNewick.setWindowTitle(QtGui.QApplication.translate("OpenNewick", "Dialog", None, QtGui.QApplication.UnicodeUTF8)) - diff --git a/ete2/treeview/_open_newick.pyc b/ete2/treeview/_open_newick.pyc deleted file mode 100644 index f1f907b..0000000 Binary files a/ete2/treeview/_open_newick.pyc and /dev/null differ diff --git a/ete2/treeview/_search_dialog.py b/ete2/treeview/_search_dialog.py deleted file mode 100644 index f02337f..0000000 --- a/ete2/treeview/_search_dialog.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- - -# Form implementation generated from reading ui file 'search_dialog.ui' -# -# Created: Tue Jan 10 15:56:57 2012 -# by: PyQt4 UI code generator 4.7.2 -# -# WARNING! All changes made in this file will be lost! - -from PyQt4 import QtCore, QtGui - -class Ui_Dialog(object): - def setupUi(self, Dialog): - Dialog.setObjectName("Dialog") - Dialog.setWindowModality(QtCore.Qt.ApplicationModal) - Dialog.resize(613, 103) - self.buttonBox = QtGui.QDialogButtonBox(Dialog) - self.buttonBox.setGeometry(QtCore.QRect(430, 60, 171, 32)) - self.buttonBox.setOrientation(QtCore.Qt.Horizontal) - self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok) - self.buttonBox.setCenterButtons(True) - self.buttonBox.setObjectName("buttonBox") - self.leaves_only = QtGui.QCheckBox(Dialog) - self.leaves_only.setGeometry(QtCore.QRect(10, 40, 211, 24)) - self.leaves_only.setChecked(True) - self.leaves_only.setObjectName("leaves_only") - self.attrType = QtGui.QComboBox(Dialog) - self.attrType.setGeometry(QtCore.QRect(330, 10, 101, 23)) - self.attrType.setObjectName("attrType") - self.attrType.addItem("") - self.attrType.addItem("") - self.attrType.addItem("") - self.attrType.addItem("") - self.attrType.addItem("") - self.attrType.addItem("") - self.attrType.addItem("") - self.attrType.addItem("") - self.label = QtGui.QLabel(Dialog) - self.label.setGeometry(QtCore.QRect(10, 10, 141, 20)) - self.label.setObjectName("label") - self.attrName = QtGui.QLineEdit(Dialog) - self.attrName.setGeometry(QtCore.QRect(150, 8, 113, 25)) - self.attrName.setObjectName("attrName") - self.attrValue = QtGui.QLineEdit(Dialog) - self.attrValue.setGeometry(QtCore.QRect(440, 10, 113, 25)) - self.attrValue.setText("") - self.attrValue.setObjectName("attrValue") - self.label_2 = QtGui.QLabel(Dialog) - self.label_2.setGeometry(QtCore.QRect(270, 10, 61, 20)) - self.label_2.setObjectName("label_2") - - self.retranslateUi(Dialog) - QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept) - QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject) - QtCore.QMetaObject.connectSlotsByName(Dialog) - Dialog.setTabOrder(self.attrName, self.attrType) - Dialog.setTabOrder(self.attrType, self.attrValue) - Dialog.setTabOrder(self.attrValue, self.leaves_only) - Dialog.setTabOrder(self.leaves_only, self.buttonBox) - - def retranslateUi(self, Dialog): - Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8)) - self.leaves_only.setText(QtGui.QApplication.translate("Dialog", "Search only for leaf nodes", None, QtGui.QApplication.UnicodeUTF8)) - self.attrType.setItemText(0, QtGui.QApplication.translate("Dialog", "contains", None, QtGui.QApplication.UnicodeUTF8)) - self.attrType.setItemText(1, QtGui.QApplication.translate("Dialog", "is", None, QtGui.QApplication.UnicodeUTF8)) - self.attrType.setItemText(2, QtGui.QApplication.translate("Dialog", "== ", None, QtGui.QApplication.UnicodeUTF8)) - self.attrType.setItemText(3, QtGui.QApplication.translate("Dialog", ">=", None, QtGui.QApplication.UnicodeUTF8)) - self.attrType.setItemText(4, QtGui.QApplication.translate("Dialog", ">", None, QtGui.QApplication.UnicodeUTF8)) - self.attrType.setItemText(5, QtGui.QApplication.translate("Dialog", "<=", None, QtGui.QApplication.UnicodeUTF8)) - self.attrType.setItemText(6, QtGui.QApplication.translate("Dialog", "<", None, QtGui.QApplication.UnicodeUTF8)) - self.attrType.setItemText(7, QtGui.QApplication.translate("Dialog", "matches this regular expression", None, QtGui.QApplication.UnicodeUTF8)) - self.label.setText(QtGui.QApplication.translate("Dialog", "Search nodes whose ", None, QtGui.QApplication.UnicodeUTF8)) - self.attrName.setText(QtGui.QApplication.translate("Dialog", "name", None, QtGui.QApplication.UnicodeUTF8)) - self.label_2.setText(QtGui.QApplication.translate("Dialog", "attribute", None, QtGui.QApplication.UnicodeUTF8)) - diff --git a/ete2/treeview/_search_dialog.pyc b/ete2/treeview/_search_dialog.pyc deleted file mode 100644 index 2f4d1f4..0000000 Binary files a/ete2/treeview/_search_dialog.pyc and /dev/null differ diff --git a/ete2/treeview/_show_codeml.py b/ete2/treeview/_show_codeml.py deleted file mode 100644 index 701e8e2..0000000 --- a/ete2/treeview/_show_codeml.py +++ /dev/null @@ -1,133 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- - -# Form implementation generated from reading ui file 'show_newick.ui' -# -# Created: Mon Sep 14 11:11:49 2009 -# by: PyQt4 UI code generator 4.5.4 -# -# WARNING! All changes made in this file will be lost! - -try: - from PyQt4 import QtCore, QtGui -except ImportError: - import QtCore, QtGui - - -class Ui_Codeml(object): - def setupUi(self, Codeml): - Codeml.setObjectName("Codeml") - Codeml.resize(594, 397) - self.model = QtGui.QComboBox(Codeml) - self.model.setGeometry(QtCore.QRect(120,110, 110, 23)) - self.model.setObjectName("model") - self.model.addItem(QtCore.QString()) - self.model.addItem(QtCore.QString()) - self.model.addItem(QtCore.QString()) - self.model.addItem(QtCore.QString()) - self.model.addItem(QtCore.QString()) - self.model.addItem(QtCore.QString()) - self.model.addItem(QtCore.QString()) - self.model.addItem(QtCore.QString()) - self.model.addItem(QtCore.QString()) - self.model.addItem(QtCore.QString()) - self.label = QtGui.QLabel(Codeml) - self.label.setGeometry(QtCore.QRect(30, 110, 91, 20)) - self.label.setObjectName("label") - self.verticalLayoutWidget = QtGui.QWidget(Codeml) - self.verticalLayoutWidget.setGeometry(QtCore.QRect(300, 10, 258, 361)) - self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") - self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget) - self.verticalLayout.setObjectName("verticalLayout") - self.ctrlBox = QtGui.QTextEdit(self.verticalLayoutWidget) - self.ctrlBox.setObjectName("ctrlBox") - self.verticalLayout.addWidget(self.ctrlBox) - self.pushButton = QtGui.QPushButton(Codeml) - self.label_2 = QtGui.QLabel(Codeml) - self.label_2.setGeometry(QtCore.QRect(10, 20, 160, 20)) - self.label_2.setObjectName("label_2") - self.workdir = QtGui.QLineEdit(Codeml) - self.workdir.setGeometry(QtCore.QRect(10, 40, 250, 25)) - self.workdir.setObjectName("workdir") - self.label_3 = QtGui.QLabel(Codeml) - self.label_3.setGeometry(QtCore.QRect(10, 60, 160, 20)) - self.label_3.setObjectName("label_3") - self.label_4 = QtGui.QLabel(Codeml) - self.label_4.setGeometry(QtCore.QRect(35, 273, 260, 20)) - self.label_4.setObjectName("label_4") - self.useprerun = QtGui.QCheckBox(Codeml) - self.useprerun.setGeometry(QtCore.QRect(10, 270, 221, 24)) - self.useprerun.setObjectName("useprerun") - self.label_5 = QtGui.QLabel(Codeml) - self.label_5.setGeometry(QtCore.QRect(35, 293, 260, 20)) - self.label_5.setObjectName("label_5") - self.display = QtGui.QCheckBox(Codeml) - self.display.setGeometry(QtCore.QRect(10, 290, 221, 24)) - self.display.setObjectName("display") - self.codemlpath = QtGui.QLineEdit(Codeml) - self.codemlpath.setGeometry(QtCore.QRect(10, 80, 250, 25)) - self.codemlpath.setObjectName("codemlpath") - self.pushButton.setGeometry(QtCore.QRect(240, 350, 51, 29)) - self.pushButton.setObjectName("pushButton") - self.retranslateUi(Codeml) - QtCore.QMetaObject.connectSlotsByName(Codeml) - QtCore.QObject.connect(self.model, QtCore.SIGNAL("activated(QString)"), Codeml.update_model) - QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("released()"), Codeml.run) - - def retranslateUi(self, Codeml): - Codeml.setWindowTitle(QtGui.QApplication.translate("Codeml", "Dialog", None, QtGui.QApplication.UnicodeUTF8)) - self.model.setItemText(0, QtGui.QApplication.translate("Model", "M0" , None, QtGui.QApplication.UnicodeUTF8)) - self.model.setItemText(1, QtGui.QApplication.translate("Model", "M1" , None, QtGui.QApplication.UnicodeUTF8)) - self.model.setItemText(2, QtGui.QApplication.translate("Model", "M2" , None, QtGui.QApplication.UnicodeUTF8)) - self.model.setItemText(3, QtGui.QApplication.translate("Model", "M7" , None, QtGui.QApplication.UnicodeUTF8)) - self.model.setItemText(4, QtGui.QApplication.translate("Model", "M8" , None, QtGui.QApplication.UnicodeUTF8)) - self.model.setItemText(5, QtGui.QApplication.translate("Model", "free-branch" , None, QtGui.QApplication.UnicodeUTF8)) - self.model.setItemText(6, QtGui.QApplication.translate("Model", "branch-site.A" , None, QtGui.QApplication.UnicodeUTF8)) - self.model.setItemText(7, QtGui.QApplication.translate("Model", "branch-site.A1", None, QtGui.QApplication.UnicodeUTF8)) - self.model.setItemText(8, QtGui.QApplication.translate("Model", "branch-free" , None, QtGui.QApplication.UnicodeUTF8)) - self.model.setItemText(9, QtGui.QApplication.translate("Model", "branch-neut" , None, QtGui.QApplication.UnicodeUTF8)) - self.label.setText(QtGui.QApplication.translate("Model", "Model to test: ", None, QtGui.QApplication.UnicodeUTF8)) - self.label_2.setText(QtGui.QApplication.translate("Codeml", "Codeml working directory:", None, QtGui.QApplication.UnicodeUTF8)) - self.label_3.setText(QtGui.QApplication.translate("Codeml", "Path to Codeml executable: ", None, QtGui.QApplication.UnicodeUTF8)) - self.label_4.setText(QtGui.QApplication.translate("Codeml", "Search for already runned data.", None, QtGui.QApplication.UnicodeUTF8)) - self.label_5.setText(QtGui.QApplication.translate("Codeml", "Display resulting info, as histogram (only for sites models.)", None, QtGui.QApplication.UnicodeUTF8)) - self.pushButton.setText(QtGui.QApplication.translate("Model", "Run", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/ete2/treeview/_show_newick.py b/ete2/treeview/_show_newick.py deleted file mode 100644 index d5b623b..0000000 --- a/ete2/treeview/_show_newick.py +++ /dev/null @@ -1,125 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- - -# Form implementation generated from reading ui file 'show_newick.ui' -# -# Created: Tue Jan 10 15:56:56 2012 -# by: PyQt4 UI code generator 4.7.2 -# -# WARNING! All changes made in this file will be lost! - -from PyQt4 import QtCore, QtGui - -class Ui_Newick(object): - def setupUi(self, Newick): - Newick.setObjectName("Newick") - Newick.resize(594, 397) - self.nwFormat = QtGui.QComboBox(Newick) - self.nwFormat.setGeometry(QtCore.QRect(200, 20, 51, 23)) - self.nwFormat.setObjectName("nwFormat") - self.nwFormat.addItem("") - self.nwFormat.addItem("") - self.nwFormat.addItem("") - self.nwFormat.addItem("") - self.nwFormat.addItem("") - self.nwFormat.addItem("") - self.nwFormat.addItem("") - self.nwFormat.addItem("") - self.nwFormat.addItem("") - self.nwFormat.addItem("") - self.nwFormat.addItem("") - self.label = QtGui.QLabel(Newick) - self.label.setGeometry(QtCore.QRect(100, 20, 91, 20)) - self.label.setObjectName("label") - self.verticalLayoutWidget = QtGui.QWidget(Newick) - self.verticalLayoutWidget.setGeometry(QtCore.QRect(300, 10, 258, 361)) - self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") - self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget) - self.verticalLayout.setObjectName("verticalLayout") - self.newickBox = QtGui.QTextEdit(self.verticalLayoutWidget) - self.newickBox.setObjectName("newickBox") - self.verticalLayout.addWidget(self.newickBox) - self.attrName = QtGui.QLineEdit(Newick) - self.attrName.setGeometry(QtCore.QRect(20, 80, 113, 25)) - self.attrName.setObjectName("attrName") - self.pushButton = QtGui.QPushButton(Newick) - self.pushButton.setGeometry(QtCore.QRect(140, 80, 51, 29)) - self.pushButton.setObjectName("pushButton") - self.pushButton_2 = QtGui.QPushButton(Newick) - self.pushButton_2.setGeometry(QtCore.QRect(200, 80, 51, 29)) - self.pushButton_2.setObjectName("pushButton_2") - self.features_list = QtGui.QListWidget(Newick) - self.features_list.setGeometry(QtCore.QRect(20, 120, 231, 251)) - self.features_list.setObjectName("features_list") - self.label_3 = QtGui.QLabel(Newick) - self.label_3.setGeometry(QtCore.QRect(60, 60, 191, 20)) - self.label_3.setObjectName("label_3") - self.useAllFeatures = QtGui.QCheckBox(Newick) - self.useAllFeatures.setGeometry(QtCore.QRect(20, 370, 221, 24)) - self.useAllFeatures.setObjectName("useAllFeatures") - - self.retranslateUi(Newick) - QtCore.QObject.connect(self.nwFormat, QtCore.SIGNAL("activated(QString)"), Newick.update_newick) - QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("released()"), Newick.add_feature) - QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL("released()"), Newick.del_feature) - QtCore.QObject.connect(self.useAllFeatures, QtCore.SIGNAL("released()"), Newick.set_custom_features) - QtCore.QMetaObject.connectSlotsByName(Newick) - - def retranslateUi(self, Newick): - Newick.setWindowTitle(QtGui.QApplication.translate("Newick", "Dialog", None, QtGui.QApplication.UnicodeUTF8)) - self.nwFormat.setItemText(0, QtGui.QApplication.translate("Newick", "0", None, QtGui.QApplication.UnicodeUTF8)) - self.nwFormat.setItemText(1, QtGui.QApplication.translate("Newick", "1", None, QtGui.QApplication.UnicodeUTF8)) - self.nwFormat.setItemText(2, QtGui.QApplication.translate("Newick", "2", None, QtGui.QApplication.UnicodeUTF8)) - self.nwFormat.setItemText(3, QtGui.QApplication.translate("Newick", "3", None, QtGui.QApplication.UnicodeUTF8)) - self.nwFormat.setItemText(4, QtGui.QApplication.translate("Newick", "4", None, QtGui.QApplication.UnicodeUTF8)) - self.nwFormat.setItemText(5, QtGui.QApplication.translate("Newick", "5", None, QtGui.QApplication.UnicodeUTF8)) - self.nwFormat.setItemText(6, QtGui.QApplication.translate("Newick", "6", None, QtGui.QApplication.UnicodeUTF8)) - self.nwFormat.setItemText(7, QtGui.QApplication.translate("Newick", "7", None, QtGui.QApplication.UnicodeUTF8)) - self.nwFormat.setItemText(8, QtGui.QApplication.translate("Newick", "8", None, QtGui.QApplication.UnicodeUTF8)) - self.nwFormat.setItemText(9, QtGui.QApplication.translate("Newick", "9", None, QtGui.QApplication.UnicodeUTF8)) - self.nwFormat.setItemText(10, QtGui.QApplication.translate("Newick", "100", None, QtGui.QApplication.UnicodeUTF8)) - self.label.setText(QtGui.QApplication.translate("Newick", "Newick format", None, QtGui.QApplication.UnicodeUTF8)) - self.pushButton.setText(QtGui.QApplication.translate("Newick", "Add", None, QtGui.QApplication.UnicodeUTF8)) - self.pushButton_2.setText(QtGui.QApplication.translate("Newick", "Del", None, QtGui.QApplication.UnicodeUTF8)) - self.label_3.setText(QtGui.QApplication.translate("Newick", "Node\'s attribute (NHX format)", None, QtGui.QApplication.UnicodeUTF8)) - self.useAllFeatures.setText(QtGui.QApplication.translate("Newick", "Include all attributes in nodes", None, QtGui.QApplication.UnicodeUTF8)) - diff --git a/ete2/treeview/_show_newick.pyc b/ete2/treeview/_show_newick.pyc deleted file mode 100644 index 3a1bab7..0000000 Binary files a/ete2/treeview/_show_newick.pyc and /dev/null differ diff --git a/ete2/treeview/drawer.py b/ete2/treeview/drawer.py deleted file mode 100644 index 77bad08..0000000 --- a/ete2/treeview/drawer.py +++ /dev/null @@ -1,119 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -import types -import signal - -from PyQt4 import QtGui -from PyQt4 import QtCore -from qt4_gui import _GUI, _PropertiesDialog, _BasicNodeActions - -import layouts -from ete2 import Tree, PhyloTree, ClusterTree -from main import save -from qt4_render import _TreeScene, render, get_tree_img_map, init_tree_style - -__all__ = ["show_tree", "render_tree"] - -_QApp = None -GUI_TIMEOUT = None - -def exit_gui(a,b): - _QApp.exit(0) - -def init_scene(t, layout, ts): - global _QApp - - ts = init_tree_style(t, ts) - if layout: - ts.layout_fn = layout - - if not _QApp: - _QApp = QtGui.QApplication(["ETE"]) - - scene = _TreeScene() - #ts._scale = None - return scene, ts - -def show_tree(t, layout=None, tree_style=None, win_name=None): - """ Interactively shows a tree.""" - scene, img = init_scene(t, layout, tree_style) - tree_item, n2i, n2f = render(t, img) - scene.init_values(t, img, n2i, n2f) - - tree_item.setParentItem(scene.master_item) - scene.addItem(scene.master_item) - - mainapp = _GUI(scene) - if win_name: - mainapp.setObjectName(win_name) - - mainapp.show() - mainapp.on_actionFit2tree_triggered() - # Restore Ctrl-C behavior - signal.signal(signal.SIGINT, signal.SIG_DFL) - if GUI_TIMEOUT is not None: - signal.signal(signal.SIGALRM, exit_gui) - signal.alarm(GUI_TIMEOUT) - - _QApp.exec_() - - -def render_tree(t, imgName, w=None, h=None, layout=None, - tree_style = None, header=None, units="px", - dpi=90): - """ Render tree image into a file.""" - scene, img = init_scene(t, layout, tree_style) - tree_item, n2i, n2f = render(t, img) - - scene.init_values(t, img, n2i, n2f) - tree_item.setParentItem(scene.master_item) - scene.master_item.setPos(0,0) - scene.addItem(scene.master_item) - if imgName == "%%inline": - imgmap = save(scene, imgName, w=w, h=h, units=units, dpi=dpi) - else: - x_scale, y_scale = save(scene, imgName, w=w, h=h, units=units, dpi=dpi) - imgmap = get_tree_img_map(n2i, x_scale, y_scale) - - return imgmap - - - diff --git a/ete2/treeview/drawer.pyc b/ete2/treeview/drawer.pyc deleted file mode 100644 index b7e0b2e..0000000 Binary files a/ete2/treeview/drawer.pyc and /dev/null differ diff --git a/ete2/treeview/ete_resources_rc.py b/ete2/treeview/ete_resources_rc.py deleted file mode 100644 index 6206af7..0000000 --- a/ete2/treeview/ete_resources_rc.py +++ /dev/null @@ -1,1864 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- - -# Resource object code -# -# Created: Tue Jan 10 15:56:56 2012 -# by: The Resource Compiler for PyQt (Qt v4.6.2) -# -# WARNING! All changes made in this file will be lost! - -from PyQt4 import QtCore - -qt_resource_data = "\ -\x00\x00\x03\x46\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x02\xc3\x49\x44\ -\x41\x54\x58\x85\xcd\xd7\x4f\x68\x1d\x55\x14\x06\xf0\xdf\x19\x13\ -\x5e\xfe\x68\x84\xe2\x9f\x5a\x6b\x8d\x6d\xa8\xba\x30\x84\x62\x5e\ -\x79\xc5\x45\x03\x6e\x5c\x74\x23\x08\x45\x44\x8a\x3b\x77\x6e\x4b\ -\x17\xae\x5c\x58\x41\x70\xe3\x26\xa0\x45\x29\x62\xd1\x95\x2e\xda\ -\x8d\xed\xaa\x69\x53\x15\x94\xa2\x22\xa8\xa5\x48\x45\x08\x06\x82\ -\x49\x5e\x6b\xde\x5c\x17\x33\x69\x1f\x2f\xff\xde\x8b\x79\xb1\x07\ -\x3e\x06\xe6\xce\xbd\xdf\x37\xe7\x9e\x99\xfb\x9d\xc0\x23\x98\xd7\ -\x79\xf4\xe3\x28\x7a\x70\x1a\x0b\x9b\x58\x63\x10\x86\x52\x4a\xda\ -\x45\x29\xf8\x2d\xcc\x95\xa4\x0b\xf8\x1b\xef\x60\x77\x87\x6b\x0d\ -\xb5\x2d\x00\x63\xf8\x04\x4b\x58\x44\x6a\xc1\x62\x39\xf6\x19\xc6\ -\xb7\x44\x00\x02\x47\x30\x55\x2e\x7e\x6b\x15\xe2\x56\xfc\x53\xe2\ -\x1b\xbc\x88\xac\x63\x01\x18\xc0\xeb\xb8\x8e\x3a\xf2\x36\x88\x5b\ -\x91\x97\x59\xf9\x03\x6f\xe0\xbe\x0d\x05\x60\x17\xde\x2e\xf7\xb4\ -\x79\xa1\xe5\x7d\x6e\x27\x03\xb7\xca\x67\xe7\x5b\x84\x2f\xe2\x3d\ -\x3c\xde\x2c\x20\x4a\x01\x73\x11\x51\xc1\xac\xa2\xba\x97\xf0\x27\ -\x7e\xc1\x4f\xe5\xf5\xb7\x12\x83\xb8\x60\xf5\x38\x82\x1b\x78\xa2\ -\xc4\x3e\x3c\x55\x5e\x77\xa2\x17\x0d\x3c\x98\x52\x9a\x8d\x88\x15\ -\x19\x38\x80\xdd\x1b\xec\xdb\xd8\x3a\x6f\x7f\x78\x83\x7a\xda\xa5\ -\xa9\x40\x31\xd4\xd3\x2c\x3f\xa5\xf4\xed\x1a\x6f\xf6\x9f\x23\x15\ -\x8c\x37\x4a\xdc\x8e\xac\x5b\x84\xed\xc6\xdd\x27\xe0\xeb\x6a\x75\ -\xef\x95\x6a\x75\xac\xf9\xde\xa5\x5a\xed\xe9\xe9\x83\x07\xf7\x6f\ -\x8b\x80\x3c\xe2\xe1\x3c\xcb\xce\x5e\x98\x98\xb8\x5d\x1f\x91\xd2\ -\xa7\x29\x62\x64\x5b\x04\x54\x2f\x5f\x9e\xc2\x4c\x5f\xbd\xfe\x02\ -\x5c\xaa\xd5\x0e\x60\xc7\xf5\x3d\x7b\xce\x6d\x8b\x80\x32\x26\x23\ -\xa5\xd7\x20\xcb\xf3\x63\x91\xd2\xa9\x97\xce\x9c\x69\x6c\x9b\x80\ -\x3c\xcb\x3e\xc6\xf3\x53\x87\x0e\x3d\x8a\xa3\x59\x4a\x1f\x74\x83\ -\x7c\x4d\x01\xb5\x8b\x17\xff\xc2\x17\xf7\x34\x1a\xa7\x53\xc4\xd5\ -\x67\xa7\xa7\x7f\xed\x96\x80\x9e\x75\xc6\x26\x53\xc4\x57\x29\xe2\ -\x95\x6e\x91\xb3\xce\x7f\x20\xcf\xb2\x19\xcc\xd6\xfb\xfa\x3e\xef\ -\xa6\x80\x95\x19\x88\xc8\xae\x8c\x8f\x8f\x66\x59\x76\x32\x52\xfa\ -\xf0\xf0\xf9\xf3\xf5\x6e\x0a\x58\x91\x81\xef\x47\x47\xfb\xf3\x2c\ -\x7b\x17\xdf\x2d\x0c\x0c\x9c\xe8\x26\xf9\x72\x74\xea\x09\x37\x75\ -\x1a\xae\xe5\x88\xee\xbe\xb3\xe0\x7f\x15\x10\x11\x7b\x23\x62\xb0\ -\x5b\x64\x11\xd1\x1f\x2d\x67\x4a\x4f\xd3\x60\x05\x3f\xa0\x12\x11\ -\x73\xf8\x5d\x61\xc5\x7e\xc4\x35\x85\x1d\xbb\x86\xca\x3a\x1c\xbd\ -\x11\xb1\x1f\xc3\x0a\x4b\x36\xac\xb0\x64\x23\x78\x0c\xf7\x23\x8f\ -\x88\x07\x52\x4a\xb3\xcb\x93\x9a\x2d\xd9\x93\x98\xc4\x4d\x77\x0a\ -\x6b\x49\x61\x30\xe7\x15\x7e\x6e\x23\x53\xda\x50\x98\xd8\xf9\x72\ -\x6e\xb3\x5d\xff\x08\xcf\xb4\x63\xcb\x77\xe0\x38\x66\xac\xde\x84\ -\xb4\x8b\x45\x85\xd1\x7d\x13\x0f\x6d\xa6\x31\xe9\xc5\xcb\xb8\xaa\ -\xb0\xdb\x4b\x6d\x90\x36\xca\x67\x7f\xc6\x31\x54\xb6\xaa\x35\x7b\ -\x0e\x5f\x96\x04\xf5\x55\x88\x6f\x96\x02\xcf\x61\x62\x4b\x5a\xb3\ -\x35\x26\x0d\x2b\x1a\x8c\x85\x26\xd4\xf1\x3e\x46\x3a\xfd\x11\x85\ -\xcd\xb7\xe7\xf7\xe2\x55\xc5\x97\x74\x4a\xd1\x2d\x77\x1a\x83\xff\ -\x02\x5c\xf1\x03\xe8\xa1\x59\x46\x9f\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x02\xef\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x10\x00\x00\x00\x10\x08\x06\x00\x00\x00\x1f\xf3\xff\x61\ -\x00\x00\x02\xb6\x49\x44\x41\x54\x78\x9c\x62\x64\x60\x60\x70\x66\ -\x60\x60\xd0\x65\x40\x02\xb9\xb9\x85\xfd\x93\x27\xf7\x17\x32\x60\ -\x01\x68\x72\x5b\x00\x00\x00\x00\xff\xff\x62\x61\x60\x60\xd0\xfd\ -\xfe\xfd\x7f\xff\xeb\x57\xaf\x19\x58\x58\x58\x18\x58\x59\x59\x19\ -\x96\x2d\x5f\xc2\xf0\xf4\xc9\xfb\x7e\x6c\x06\xac\x5b\xbf\x86\xe1\ -\xd2\xe5\x5b\xfd\xdc\x5c\xbc\x7f\x95\x95\x25\x19\x00\x00\x00\x00\ -\xff\xff\x04\xc1\x31\x0e\x40\x40\x10\x86\xd1\x2f\x64\x1a\x7b\xff\ -\x6b\x28\x68\x48\xdc\x41\x42\xbd\xb1\xab\x63\x54\x3f\xf5\xc4\x7b\ -\x0d\x80\xf4\xe1\x7e\x21\x09\xbd\x22\x22\x98\xe6\x85\x9c\x0f\x00\ -\x86\xb1\x67\xdb\x57\xea\x59\x30\x33\x1e\xbf\xe9\x52\x6a\x01\x7e\ -\x00\x00\x00\xff\xff\x34\xcc\xb9\x0d\x80\x30\x10\x00\x30\xdf\x35\ -\xc0\x02\x11\x1d\x8a\xb2\xff\x4e\xc0\x1c\x79\xa8\xf0\x00\xce\x7f\ -\x8e\x48\x73\x4e\xbd\x0f\x99\xa9\xd6\x4b\x6b\xd5\xf3\xde\xa0\x94\ -\x13\x1c\xfb\x66\x2d\x32\x02\x7c\x00\x00\x00\xff\xff\x3c\xcc\xb1\ -\x09\x00\x30\x0c\xc4\x40\x75\xf9\x2d\x02\xc9\xfe\x73\x04\x3c\x93\ -\xdf\x4e\xe7\x56\x70\x9a\x41\xd3\x54\x17\xce\x44\x12\xf7\xec\xc1\ -\x00\x11\x0f\x80\x25\x61\x7b\xfa\x07\x00\x00\xff\xff\x62\x81\xb3\ -\xfe\xff\x67\x60\x64\x60\x64\x60\x60\x64\x60\xf8\xfb\xf7\x37\xc3\ -\xd3\x67\xcf\x18\x7e\xfe\xf8\xc9\xa0\xad\xa3\xc3\xa0\xa2\xa2\x0a\ -\x57\x76\xed\xda\x65\x06\x01\x41\x41\x38\x1f\x00\x00\x00\xff\xff\ -\x42\x18\xc0\xc8\xc8\xc0\xc8\x04\x71\x16\x2b\x2b\x3b\xc3\x99\x33\ -\x27\x19\x18\x19\x19\x19\xae\x5e\xbb\xc4\xc0\xc4\x04\x71\xe8\xbf\ -\x7f\xff\x18\x18\x19\x19\x19\xb8\x38\xb8\xe1\xda\x00\x00\x00\x00\ -\xff\xff\x82\x1b\xc0\xca\xca\xc1\xf0\xe4\xc9\x13\x06\x06\x06\x06\ -\x06\x79\x79\x45\x6c\x11\x00\x07\x1c\x5c\x9c\x70\x36\x00\x00\x00\ -\xff\xff\x42\xb8\x80\xe1\x3f\x83\xad\xad\x39\x5e\x8d\x30\x70\xe5\ -\xca\x6d\x38\x1b\x00\x00\x00\xff\xff\x82\x1b\xf0\xef\xdf\x3f\x06\ -\x06\x06\x06\x86\x37\xaf\xdf\xe3\xd5\x2c\x22\x2a\xc8\xf0\xef\xff\ -\x7f\x38\x1f\x00\x00\x00\xff\xff\xc2\x30\x40\x44\x54\x10\x53\x17\ -\x1a\xf8\xff\x0f\x61\x00\x00\x00\x00\xff\xff\x62\x41\x17\x24\xca\ -\x05\x50\xcb\x18\x18\x18\x18\x00\x00\x00\x00\xff\xff\x4c\xcc\xb1\ -\x0d\x00\x20\x0c\x03\xc1\x77\x26\x48\xc1\xfe\x7b\x12\x29\x98\x06\ -\x10\xd5\x75\xf7\x82\x59\x65\x13\xca\x91\xc8\x80\x4e\x0c\xc8\x57\ -\xd3\x2b\xf0\x17\x6e\x00\x00\x00\xff\xff\x62\x61\x60\x60\x60\xd8\ -\xb7\x7f\xf7\xfb\x3f\xdf\xfe\xb0\xde\x5a\x7d\x8e\xe7\xff\xdf\xff\ -\x0c\xcc\x4c\x4c\x0c\xff\xff\xff\x67\xf8\xfd\xef\x2f\xc3\xcf\xdf\ -\xbf\x19\x7e\xfd\xfa\xc5\xf0\xe3\xd7\x2f\x86\x1f\x3f\x7e\x32\xfc\ -\xf9\xff\x8f\xc1\x25\xd3\x13\x6e\x00\x00\x00\x00\xff\xff\x34\xcc\ -\x3b\x11\x80\x30\x10\x40\xc1\x97\x0b\x3d\x83\x10\x44\x90\x19\xec\ -\xa4\xa0\x43\x40\xb4\xa0\x8f\xf6\x3e\x5c\x2a\x56\xc0\x2e\x00\xed\ -\x38\x37\x80\xf1\xdc\xaf\x50\x90\x2a\x64\x42\x7c\x81\x79\x60\x6e\ -\xa8\x1b\xaa\x4e\x92\xf4\xfd\x5a\xff\x60\x02\x00\x00\xff\xff\x62\ -\x64\x80\x64\x67\x1b\x06\x06\x06\x51\x82\xa1\x87\x0a\x5e\x33\x30\ -\x30\x1c\x01\x00\x00\x00\xff\xff\x03\x00\x84\xe9\xd3\x92\xa9\xe2\ -\xf6\x22\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x06\x67\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x05\xe4\x49\x44\ -\x41\x54\x58\x85\xc5\x97\x7b\x4c\x53\x57\x1c\xc7\xbf\xe7\xb6\x52\ -\xfa\xb0\x40\x29\x6d\x51\x4b\xa7\x05\x1c\x65\x38\x37\x04\x63\x86\ -\xaf\x3d\x7c\x3b\xdd\x94\xa9\x89\xaf\x99\xac\x30\xb6\x64\xc4\x3d\ -\xe2\x63\x0e\x5d\x7c\xcc\x64\x71\xfc\xb1\x99\x79\x99\x9a\x6c\x71\ -\x4e\x97\x45\x37\x9d\xce\xf7\x64\x83\xb0\x30\xc4\x28\xe2\x13\xf0\ -\x41\x69\x2b\x45\xdb\x22\x7d\xdd\xc7\xd9\x1f\x80\x13\x10\x5b\x74\ -\xba\x5f\x72\x72\xd3\x73\x7e\xfd\x7d\x3f\xe7\xf7\x3b\xe7\x9e\x73\ -\x09\x80\x44\x00\x6d\xf8\x7f\x4c\x29\x05\xd0\x46\x29\xf5\x46\xe2\ -\x4d\x08\xe9\x97\x3d\xb9\x60\x7e\xe6\x88\x8c\xc9\xaa\x28\xa2\x6b\ -\x6d\xf3\xb7\xf2\x5c\xe0\xc6\xb5\xba\x2b\x7b\x0f\xef\xf9\xe6\x70\ -\x5f\xd5\x09\x21\x20\x00\xd4\x91\x00\x4c\x59\xb8\xea\xbd\x14\x53\ -\xfc\x72\x99\x3a\x51\x6a\xf3\x46\x3b\x9d\x3e\x45\x93\x52\xc6\xf8\ -\x64\xd4\x4b\x89\xef\xba\xa2\xb5\xa9\x86\xf7\x78\xef\xac\x2c\x3b\ -\xb4\xb3\xba\x0f\x00\xea\x88\x00\x72\xf3\xd7\x6d\x7f\xca\xa8\x9b\ -\x53\xc7\xe4\x34\x4a\x35\x69\x0e\x10\xb8\x29\xe0\x01\xe0\x21\x80\ -\x9b\x10\xb8\xfd\x2d\xf5\x9c\xbf\x72\xe3\x4b\xcd\xf6\x6b\x25\xa7\ -\xcb\x7f\xdb\x17\x29\x00\x13\xce\xe9\xd5\x37\x57\xae\xd7\x26\x24\ -\xcc\xbb\x1a\xb7\xc0\x21\x8d\x4f\x6b\x05\xc0\x81\x82\x27\x14\x3c\ -\x03\x70\x14\xe0\x44\x0a\x3e\x3a\x7e\x88\x27\x6e\xd2\x96\xed\x02\ -\xa3\x9c\x38\xf4\x99\x11\x99\x11\xa5\x00\x80\xf4\x41\x83\x2a\x95\ -\x21\x61\x5e\xfe\x87\xef\x36\x27\xcc\x71\x33\xd2\xe8\x10\x00\x0e\ -\x04\x3c\xa5\xe0\x80\xf6\x46\x00\x9e\x00\x1c\x44\xf0\x8d\x87\x3f\ -\x9a\x16\xf2\xda\x5e\x89\x8d\x8d\x19\xc9\xb2\xec\x4f\x9d\x71\x44\ -\x51\xdc\x96\x9f\x9f\x7f\xb3\xcf\x00\x33\x97\x2c\x2d\xe2\xd4\x4f\ -\x47\x31\xd1\x31\x9e\x4e\x71\x50\x70\x84\x80\x27\xb4\x3d\x13\x22\ -\xf9\x17\x26\x4a\x1e\x73\x2b\x31\x79\xc4\x01\x4f\x1b\x57\xbe\x61\ -\xe3\xa6\x96\x86\xba\x0b\xbf\x3e\x52\x06\x82\xc1\x60\x4e\x40\xfb\ -\xb2\x8f\x69\x17\xe0\x3b\x85\x28\xc0\xd5\x1f\x5c\x3e\x5e\xf4\xb9\ -\xe4\x04\x42\x88\x88\x9c\x00\x91\xe3\x42\xbe\x5b\x72\x4d\xa2\xf9\ -\x68\xca\x1b\x5b\xca\x2b\xd6\xa6\xe6\x02\x78\x34\x00\x51\x22\x57\ -\x49\xa4\xb2\xbb\x33\xec\xcc\x02\x43\xc1\xf1\x7e\xb7\xcc\x3c\x65\ -\xe3\x0e\x46\xae\x71\x12\x06\x6e\x00\x9e\xe6\xe3\x45\xd9\xd4\xe7\ -\x88\x15\x00\x4e\xab\xd5\x2a\xc3\x89\x87\x07\x10\x78\x41\x72\xef\ -\xec\x29\x78\x4a\xc0\x51\x02\x5e\xc7\x07\x98\x91\x57\x4b\xb5\x55\ -\x69\x33\x1b\xc5\x0e\x38\xde\xef\x8a\x6f\xae\xaf\x9a\xe2\xd9\x92\ -\xf3\x6c\x9c\x5a\x19\xc3\xb2\xec\x1d\xe0\x11\xd6\x40\xcb\xed\xd6\ -\x46\x03\x60\xae\xfe\x6e\xf1\x60\x65\x6c\x62\x10\x94\xe7\x88\xc8\ -\x09\x84\xf2\xdc\xdc\x96\x4b\xda\xd7\xab\xbf\x1d\x55\x93\x3c\xe1\ -\x54\xa0\x9f\x82\x07\xc0\x47\xa9\x07\xd5\x46\x2b\x6a\x33\x24\x0c\ -\xbd\xad\x54\x2a\x40\x29\x75\x03\x80\x20\x08\xc2\x43\x65\xc0\xdb\ -\xdc\x70\xc9\x00\x24\xc9\x54\x5a\x3e\x75\xfa\x86\x2a\xa0\x7d\xff\ -\x13\x02\xb7\x76\xeb\xc4\x45\x72\xde\x2f\xe3\xa4\xb2\x10\x6d\xcf\ -\x0e\x27\xfa\x5b\xe2\x34\xba\x81\xb5\x12\x89\x7c\x8f\x4a\xe9\x9b\ -\x2d\x08\xc2\x5e\x00\x70\xb9\x5c\x9e\x87\x02\x68\x3c\x7b\x62\x73\ -\xbc\x65\xc7\x48\x50\x31\x01\x1d\xa5\x60\x3a\x4a\xb1\x3b\x5a\xe3\ -\x3d\x6a\xca\xaa\xbe\x79\x6a\xdb\x30\xf0\x3e\x1f\xb8\xb6\xb6\xc0\ -\xed\x1b\x66\x59\x14\xe3\xcc\x48\x89\x9b\x74\xba\xea\xd2\xfe\x82\ -\x82\x02\xc7\x83\xe2\x87\x05\x70\xb9\xec\x67\xd3\x46\xcd\xfc\x5b\ -\xaa\x36\x0d\xb9\x5b\xff\x8e\x7d\x4f\xb2\x16\x1d\xb3\x35\x96\x9b\ -\xe0\x77\xaa\x88\x10\x0c\x42\x08\x04\x45\xee\x8e\x3e\x10\x0c\xf1\ -\xc1\x40\xbc\xa2\xb4\xb4\xf4\x97\x70\xe2\x00\xc2\x9f\x05\x84\x10\ -\xe5\xf0\x9c\x19\x17\xcc\x73\x77\x55\x31\x52\xd9\x6d\x42\xe0\x16\ -\xd1\xbe\xea\x09\xe9\x78\x52\xb8\x09\xe0\x09\xfd\xb9\x74\x46\x82\ -\x32\x30\xaf\xa9\xf1\xc6\xc2\x7d\xfb\xf6\x55\x84\x15\x8f\xf4\x2c\ -\xf8\x74\xed\xda\xf5\x15\x67\x1a\xc7\xc5\xa4\x4e\xf5\x0b\x49\xd3\ -\xab\xd0\x71\x06\x80\xc2\x23\x32\x70\xfb\x3d\x36\xdf\x80\x6b\xc5\ -\x1f\x18\x34\x8a\xb1\x01\x7f\xe0\x68\x72\xb2\xb9\xcb\x81\xc4\xf3\ -\xfc\xd7\xf7\x2b\x07\x21\x44\xdd\xa5\x04\x6b\xd6\xac\x61\xf4\x7a\ -\x7d\x52\x77\x47\x83\x4e\xe7\x3f\xf8\xe3\xaa\x71\x93\x66\x09\x9f\ -\x28\x6f\x1c\x9b\x60\x1c\x92\xca\x08\xe8\xd7\x12\x0c\x86\xdc\x3a\ -\x95\xa8\x6f\x71\x36\x18\xb4\x71\xfd\x53\x0d\x7a\x83\xc0\x30\x64\ -\x00\x80\x2e\x00\xcd\xcd\xcd\xae\xde\x26\xd7\x05\xc0\x62\xb1\x48\ -\xdd\x6e\xf7\xb8\xfb\xf8\x29\x29\xa5\x21\x00\x1f\x13\x42\x56\x27\ -\x5b\x32\x73\x92\xcc\x69\x66\x5d\x7c\x4c\x6c\xcd\xb5\xfa\xeb\xe5\ -\x27\x0e\x1e\x9a\x3f\x7f\xe1\xee\x94\x94\xd4\x89\x7a\xbd\x2e\xf9\ -\xe4\xc9\xdf\x4b\xd6\xad\x5b\x67\xeb\x4d\xb4\x4b\x16\x10\x41\x09\ -\x58\x96\x5d\x66\xb5\x5a\x3f\xeb\xd6\xf7\x3e\x80\xfe\x9d\xbf\x2f\ -\x5f\xbe\x32\x50\xa3\x89\x5f\x92\x99\xf9\x3c\xe3\xf5\x7a\xd9\xd9\ -\xb3\x67\xe5\x85\x15\xef\x5e\x82\x3e\x5a\x3f\xab\xd5\xba\xfa\xde\ -\x0e\xab\x35\x2f\xcd\x68\x34\xbe\x60\x34\x0e\x5a\x58\x5c\x5c\xfc\ -\x55\x61\x61\xe1\x99\x70\x41\x1e\x05\xa0\x87\x29\x14\xf2\x32\x9b\ -\xcd\x36\x4a\xaf\xd7\x47\x9b\x4c\xa6\x5d\x2c\xcb\xee\x02\x00\xbb\ -\xdd\xbe\xb6\xa8\xa8\x88\x7f\x68\x00\x4a\xe9\x60\x96\x65\x57\x77\ -\xeb\xee\xb1\x58\xd3\xd3\xd3\x0f\x54\x57\x9f\x9e\x66\x34\x1a\x2d\ -\x66\xf3\x90\xa1\x0e\x87\xc3\x24\x91\x48\x2e\x5a\x2c\x16\xda\x5b\ -\xec\x88\x00\xf2\xf2\xf2\x7a\xd4\x93\x65\xd9\x65\xf7\x71\xd5\x78\ -\x3c\x9e\x8d\x36\x9b\x6d\xab\x5e\xaf\x93\x26\x25\x25\xa5\x57\x56\ -\x56\xbe\x63\xb5\x5a\x1f\xee\x2c\x08\x63\xb2\x92\x92\x92\xe1\xf7\ -\x76\x50\x4a\x0d\x63\xc7\x8e\x39\x51\x5e\x5e\xf1\xb3\xd1\x38\x68\ -\x56\x7a\x7a\x7a\x56\x43\x43\xc3\x62\x00\x9b\x7b\x0b\x12\xf6\x4e\ -\xf8\x00\xdb\x25\x8a\xa2\xe1\xde\x86\x8e\x5d\x71\xfe\xfc\xf9\xcf\ -\x6d\xb6\x26\xde\xe5\x72\x21\x2b\x2b\xab\x30\x3b\x3b\x5b\xdd\x5b\ -\x90\x88\xaf\xe5\x91\x58\x49\x49\xc9\x6b\xa2\x28\xd6\xcb\x64\xb2\ -\x8b\x15\x15\x7f\xed\x1e\x3f\xfe\xc5\xe9\x19\x19\xe9\x38\x77\xee\ -\xdc\xea\xdc\xdc\xdc\x35\x3d\xc4\x23\xb9\x15\xf7\xc5\x44\x51\xbc\ -\x43\x08\x99\x15\x0a\x85\x0a\x55\x2a\x55\x53\x93\xdd\x2e\x3a\x9d\ -\x37\x31\x6c\xd8\xb0\x82\x05\x0b\x16\x98\x7a\xfb\x9f\x9a\x52\x8a\ -\xc7\xd1\xde\xb2\xbe\xbd\xff\xfb\x9d\x3f\xd0\xda\xda\xf3\xf4\xc8\ -\x91\x23\x5f\x76\x1f\x07\xf0\xdf\x66\xa0\xbb\x9d\xab\x39\xbb\xc9\ -\x6e\x77\x08\x0e\x87\x03\x29\x29\xa9\x4b\x56\xac\x58\xf1\x5c\x77\ -\x9f\xc7\x0a\x50\x56\xf6\xc7\xf1\xda\xda\xda\xa3\x76\x87\x13\x7e\ -\xbf\x4f\x3e\x75\xea\xd4\x95\x4f\x14\x00\x00\x6a\xce\x9e\xf9\xc2\ -\xe1\x70\x08\x57\xea\xea\x5b\xeb\xea\xea\x7a\xbc\x9a\x09\x9e\xc0\ -\xe7\xf9\xe8\xd1\x63\x66\x13\x82\x33\xa5\xa5\xa5\x97\xba\x0d\x29\ -\xff\x01\xd2\xca\x14\x12\x68\xa2\xe9\xf4\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xeb\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\ -\x06\x62\x4b\x47\x44\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\ -\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\x01\ -\x42\x28\x9b\x78\x00\x00\x00\x07\x74\x49\x4d\x45\x07\xdb\x03\x10\ -\x0f\x18\x26\xf8\xde\x31\x9a\x00\x00\x01\x6b\x49\x44\x41\x54\x58\ -\xc3\xed\xd7\x3d\x4b\x1c\x61\x10\x07\xf0\x9f\x22\x18\x39\x10\x84\ -\xa4\x91\xf8\x52\x88\x85\xb5\xbd\x81\xc4\xcf\x60\x9a\x80\x85\x58\ -\xf8\x86\xe0\x87\x50\xdb\x20\x58\x99\xf4\x21\x89\x06\x2c\xfd\x00\ -\xda\x58\x44\xc4\xc2\xca\x4a\xd1\xc2\x46\xf1\x05\x83\x36\x73\xb0\ -\x59\x96\xf3\x8e\xbd\xdd\x6b\x6e\x60\xd8\xd9\xd9\xd9\x9d\xff\xbc\ -\x3c\xb3\xcf\x43\x31\xb4\x84\xe7\xe0\xc5\x5a\x86\x1d\xe8\xcd\xe9\ -\xac\x82\xf3\xd4\x37\x4f\x30\x12\xf7\xa7\x18\x0b\x30\x85\x50\x3a\ -\x80\xc9\x70\xf6\x13\xbf\x42\xfe\xd4\x0c\x47\x5f\xb0\x9f\xe2\xed\ -\x0c\x00\x7f\xc2\xe9\x04\x3e\x84\xbc\xd3\x0c\x00\x5b\x78\xc4\x61\ -\x0d\x00\x43\xf8\x87\xbf\x09\xdd\x11\x9e\x30\x98\x17\xc0\x72\x44\ -\x33\x5c\xa3\x04\x6b\x61\x33\x9b\xd0\xcd\x86\x6e\xb5\x68\x00\xdd\ -\xb8\x4a\x74\x7f\x9a\x2f\xc3\xe6\x3f\xea\x6c\x62\x33\x7e\xc6\x5b\ -\xec\xc5\x4a\x48\xf2\x1e\xde\x61\xaa\x48\x00\xf3\x71\xfd\x96\xf1\ -\xac\xaa\x5b\x28\xba\x07\x1a\xa6\x4e\x2d\xa6\x36\x80\x36\x80\x2e\ -\xbc\x69\xc0\xb6\x10\x00\x77\xad\xce\xc0\x7a\x9d\xb6\xe3\xf8\xd8\ -\x4a\xb0\xed\x41\xd4\x06\x50\x0f\xa5\xf7\x00\x8f\x38\xc3\x77\xf4\ -\x97\x99\x81\xea\x3e\xa0\x0f\x9b\x98\xc6\x8f\x56\x94\xe0\x16\x1b\ -\x89\x65\x5c\x3a\x80\x0a\xe6\x42\x3e\x28\x6d\xbc\x66\x1c\x42\x1e\ -\xb0\x92\x37\x03\xd5\x7f\xc6\xfb\x18\x46\xc3\x18\x78\xa5\x07\x7a\ -\x62\x80\x75\xe3\x6b\xde\xa8\xb6\x33\xba\xfc\x22\x35\x09\x9f\x33\ -\xa2\xaf\x84\xee\x21\x6f\x09\x7e\x47\x44\xfb\xb8\x0f\xdd\x4d\x1d\ -\x59\x9b\x09\xf9\xb8\x8c\xb3\x61\xd6\x79\xe0\x1a\xbb\x18\x2d\xa3\ -\x09\x3b\x1a\x7d\xe1\x05\xf6\xfd\x58\x98\xa3\x51\x4d\x65\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x77\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x02\xf4\x49\x44\ -\x41\x54\x58\x85\xed\xd6\x4f\x68\x5c\x55\x14\x06\xf0\xdf\x99\x49\ -\x6a\xff\xa6\x75\xe1\xa2\x55\x5a\x63\x2d\x14\x8a\x20\xc4\x66\x22\ -\x8a\x64\x25\xe2\xa2\x60\x29\x74\xa7\x14\x17\x52\x10\xba\xb2\x8b\ -\xae\x0a\xe2\x46\x11\xb3\xb1\x2e\x04\x11\x51\x24\x54\x5c\x58\xa9\ -\xee\x52\x10\xd3\xa4\x0d\xc5\xba\x71\xa1\x26\xf5\x7f\x45\x14\x0c\ -\x1a\x52\xc7\x99\xe3\xe2\xbd\x69\x27\x63\x26\x61\xb4\xd0\x4d\x3e\ -\x38\x3c\xde\x7d\xf7\xde\xf3\x9d\xfb\xce\xf9\xce\x0d\x6c\xc7\x9f\ -\x7a\xc3\x3d\xd8\xb1\xcc\xf8\x35\x5c\xec\x61\x9f\x4d\x30\x90\x99\ -\x7a\x31\x8c\x21\x97\xb1\x2b\x3d\xee\x33\x50\xe9\x31\xf2\x9b\x8e\ -\x35\x02\x6b\x04\x6e\x39\x81\xbe\xf6\x97\x88\xd8\x8d\x03\xb8\x82\ -\x39\xcc\x65\xe6\xef\xff\xd7\x49\x44\xdc\x86\x5d\xb8\x1b\x83\xf8\ -\x2e\x33\xcf\xfe\x8b\x00\xf6\xe2\x79\xa5\x40\x94\x8b\x17\xf0\x03\ -\xbe\xc6\x17\x25\xb1\xc1\x2e\xbe\xd6\x47\xc4\xd3\xa5\xa3\xbd\xd8\ -\x83\x9d\xd8\x86\x28\xe7\x24\x5e\xc5\xd9\xd6\xa2\x81\x0e\x71\xd8\ -\x82\x63\xf8\x11\x0d\x4b\x85\xa6\x81\x05\xd4\x2d\x2f\x44\x4d\x85\ -\xaa\x76\x7e\xaf\x63\x11\xa7\x70\x6f\xbb\x10\xc1\xc0\xc4\xe8\x68\ -\xdf\xcc\xd0\x50\x7f\x3b\x91\x93\xfb\xf6\xad\xdb\x50\xad\x1e\xc2\ -\x05\xfc\xb5\x82\xd3\x95\x6c\x01\x3f\xe3\x39\x6c\xed\xaa\x84\xeb\ -\x17\x17\x0f\xd4\xfb\xfb\x2f\xb5\x9f\xe5\x63\x9b\x37\x7f\x78\x6e\ -\x68\x68\x6b\x66\x0e\x63\x04\xef\xe3\xef\x32\x92\x95\xd0\x28\xc9\ -\x5e\xc6\x53\xd8\x91\x99\x2f\x75\xcb\xa5\x0a\xf4\xd7\xeb\x67\x22\ -\xf3\x8e\x8b\xc3\xc3\xfb\x61\x7a\x64\xe4\x2e\xd4\x16\x36\x6e\x1c\ -\x87\xcc\xbc\x94\x99\x87\x15\xff\xf3\x15\x45\xd3\xc9\x8e\xbd\x5a\ -\x51\x7f\x80\x87\x33\xf3\xfe\xcc\x3c\x9d\x99\x8d\x95\xd8\x56\x60\ -\x68\x66\xa6\x1e\x99\x6f\x66\xc4\x11\x88\xcc\x27\xf1\xde\xe8\xc4\ -\xc4\x1f\x4b\x3c\x64\xfe\x94\x99\x27\x70\x3b\x9e\x51\x54\x4b\x43\ -\xf1\xdf\x5f\xc6\xce\xcc\x3c\x98\x99\x17\x56\x39\xa5\xeb\x08\x45\ -\x12\xce\x4f\x8f\x8c\xec\xc1\x74\xb3\x52\xb9\xb3\xd2\x6c\x7e\xd6\ -\xac\x54\x8e\x3c\x38\x39\x39\xb9\xea\x06\x11\x8f\xe2\xd3\xcc\xec\ -\xb5\xa5\x8b\x88\x1b\xdd\xb0\x36\x35\xf5\x25\x2e\x47\xe6\x8b\x68\ -\xac\xe6\x3c\x22\x1e\x88\x88\xd3\xf8\x08\xe7\x23\xe2\x70\x44\x74\ -\x96\xf5\xaa\x58\xa2\x84\x91\xf9\x7a\x64\x3e\x8b\x37\xba\x38\xad\ -\x44\xc4\x13\x11\x31\xab\xa8\x8e\x83\xe5\x1e\xf7\xe1\x1d\xcc\x47\ -\xc4\xf1\x88\xd8\xf6\x5f\x09\x7c\x82\x7a\xa3\x5a\x7d\xab\xc3\xf1\ -\x96\x88\x38\x86\xef\xf1\xae\x42\x88\xa2\x63\x7d\x15\x1b\x70\x12\ -\x57\x23\xe2\x54\xa9\xac\xab\xa2\x10\x22\x62\xaa\x56\x1b\x9b\x1e\ -\x1e\x1e\x6f\xab\xd3\x5d\x8a\xac\x5f\x28\xad\x17\x0d\xb8\xa6\x28\ -\xdb\x8f\xf1\x48\xb7\x1b\x51\x60\x60\xaa\x56\xa3\x90\xd8\xd9\x46\ -\xb5\x7a\xe8\xa1\xc9\xc9\xed\x38\x81\xc7\x15\x59\xbe\xae\x83\x74\ -\xa3\x8c\xb8\x13\xad\xd2\x8c\xb6\xb1\x66\x49\x64\x16\x2f\x60\x3c\ -\x33\xeb\x14\x49\x78\xe3\x04\x0a\x46\xfb\xf1\x79\x5b\x14\xcd\xb6\ -\xe7\x2f\x8a\x0b\xe7\xdb\x38\xdf\x25\xea\xdf\xf0\x1a\xce\xe1\x5b\ -\x85\x82\xb6\x24\xbc\x35\xe7\x57\x1c\x6d\x9d\x40\x67\xd6\xf6\xe1\ -\x2b\x45\xa3\x98\x2d\x4f\x65\x0e\xdf\xb4\x58\x97\xcc\xc7\x14\xea\ -\xd8\x89\xf9\xcc\x3c\xda\x36\x2f\x14\xb7\xee\xc1\x36\xdb\xad\xe8\ -\x37\xd7\xb1\x76\x2b\x5e\x23\xb0\x46\xe0\x96\xa2\xe7\xee\x55\xe2\ -\x0c\xae\x2e\x33\xde\xf3\x0d\xba\x25\x14\x3d\xf7\xf2\x9b\x84\x4d\ -\xff\x00\x91\x41\xf9\xf6\x95\xca\x13\xf1\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x16\x7c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x38\x00\x00\x00\x3f\x08\x06\x00\x00\x00\xb5\x83\x0b\xa6\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x15\xf9\x49\x44\ -\x41\x54\x68\x81\xcd\x9a\x7b\x94\x9d\x65\x7d\xef\x3f\xdf\xe7\xd9\ -\x7b\xae\x99\x64\x92\x99\xcc\xec\xb9\x24\x21\x21\x04\x48\x22\x18\ -\x0c\x37\xe5\x22\x58\x44\xd0\xda\x5a\x8b\xb7\xb3\xe0\x48\x75\x95\ -\x7a\xf4\xe8\x29\xb6\x26\x3b\x9e\xae\x34\xa7\x8b\x4c\x20\x8a\xf5\ -\x52\x2a\xa2\xad\x96\x65\xd5\x63\x8b\x4a\x75\x29\xe0\x05\x01\xeb\ -\x51\xe4\x20\x20\xe1\x9a\x0b\xb9\xcd\x3b\x93\xfb\x24\x33\x99\x3d\ -\x7b\xbf\xcf\xf7\xfc\x31\x13\x1a\x20\x93\x84\xcb\xd1\x7e\xd7\xda\ -\xff\xed\xf7\xf7\xfc\xbe\xef\xef\x7d\x7e\x77\xd9\xe6\x3f\x13\xb2\ -\x72\xa9\x00\x9c\x03\xcc\x02\xa6\x02\x3b\x01\x03\xa3\xc0\xe3\xa5\ -\xbe\x6c\xc3\x8b\x91\x17\x5e\x71\x0d\x5f\x06\xb2\x72\xe9\x74\xe0\ -\x5d\x51\xa9\x96\x92\xa6\x63\xba\x6c\x9d\x8d\x3c\x27\x3a\xd5\xd9\ -\xa1\x37\x2b\x97\xce\x7b\x31\x32\xf5\x9f\xc1\x82\x59\xb9\xd4\x05\ -\xbc\x09\xb1\x49\xb0\x10\xfb\xad\x48\x05\x27\x07\x14\x6a\xb2\x2b\ -\x06\x63\x36\x5b\xe1\x6b\x52\x1a\x28\xf5\x65\x4f\x1d\x8f\xec\xdf\ -\x39\xc1\xac\x5c\xba\x30\xe1\x8e\x42\x62\x2c\x0f\xf1\xaa\xe0\xd4\ -\x99\xe4\x7a\x11\xda\x30\x35\x64\x23\x81\x53\x05\x69\x83\x93\xef\ -\x90\xf4\x0c\x70\x5f\xa9\x2f\x1b\x3a\x96\xfc\xdf\x19\xc1\xac\x5c\ -\x8a\xc0\xbb\x05\x5b\x8d\x2e\x15\xe9\xc2\x44\x28\x06\xbb\x55\xc1\ -\xca\xcd\xaf\x92\xf5\x95\x18\x52\x51\x84\x33\x80\x77\x26\x7b\x17\ -\x0e\x83\xa0\x5b\xa4\x54\x04\x7e\x50\xea\xcb\xc6\x8e\x76\x4e\xe1\ -\xff\x83\xe2\x2d\xc0\x12\x60\x11\xd0\x06\x6c\x03\x7e\x5c\xea\xcb\ -\x9e\x79\xde\x5f\xdf\x26\x79\x53\xb2\x3f\x04\x9a\x2f\xd3\x28\xb9\ -\xd9\x81\x8d\x86\x9b\x87\x87\xa7\x7e\x6b\xfe\x67\x9e\xaa\x00\xac\ -\x5b\xa5\x1f\xb4\x55\x3a\x66\x23\x9d\x87\xd3\x01\xa1\x3f\x51\x8d\ -\x4f\xba\xc0\x42\xe0\xd7\x47\xd3\xe7\x15\xb3\x60\x56\x2e\xbd\x0a\ -\x58\x06\x74\x27\x14\xa5\xe4\x60\x39\xa1\x83\xc2\x39\xf0\x91\x43\ -\x1e\x30\x2b\x97\xce\xb6\xd4\x16\x92\xdf\x66\x38\x13\x31\x05\xa8\ -\x46\xd2\x57\x2b\x95\xfa\x9b\x7a\x6f\xdc\xb2\xfb\xf9\xf2\x37\x7e\ -\xbc\xb3\xb3\xd1\xe1\x0b\xb2\x17\x00\x0f\x58\xba\x0f\xfb\xc9\x52\ -\x5f\xf6\xe3\xa3\xe9\xf5\x8a\x58\x30\x2b\x97\xa6\x01\x9f\x00\xf5\ -\x82\x1b\xa3\x1c\xec\x90\x12\x04\x61\x03\x8f\x01\x57\x01\x7f\x3d\ -\xf1\xc8\xd9\xe0\x7a\x02\x67\x82\x9b\x65\x1d\x10\xfe\xab\x99\x6b\ -\x76\x7c\x97\x49\xde\x78\xbd\x75\x09\xc9\xed\x46\xc9\x38\x45\xa5\ -\xe6\x84\xd2\xb1\x74\x7b\xa5\xc2\xc4\xc5\x46\xad\xc0\x0c\x4b\x7b\ -\x30\x5b\x4d\x7a\x5a\xf2\x93\x40\xc1\xd0\x02\x9c\x00\x90\x95\x4b\ -\x6d\x82\x3d\x4a\x3e\xc7\xa6\x41\x96\x72\xeb\xfa\x8e\xbe\x81\x7f\ -\x9b\x8c\xdc\xe6\x65\xed\x67\x04\xf3\x41\x4b\x2d\x4e\x7e\x10\xd4\ -\x30\x56\x0b\x77\x03\x23\xbf\x2d\x82\xa7\x0a\x9a\x80\x1c\xeb\xae\ -\x1a\x2a\x57\xd1\x9f\x81\x36\x00\x12\xd4\x03\x33\xb2\x72\xa9\x0e\ -\x38\x33\x27\x0c\x2a\x68\x16\x56\x9d\xd1\xc6\x27\x1b\xb3\x6f\x1e\ -\x4d\x78\x31\xd4\x2d\x96\x68\x00\x3f\xa8\x48\x43\x24\xbf\xbf\x10\ -\x3d\x0f\x18\xce\xca\xa5\x19\xbf\x0d\x82\xe9\xd0\x65\x16\x79\x7f\ -\x4f\x5f\xff\xbd\xb3\xfb\xb2\x0d\x24\xc7\x09\x93\x34\xd9\x1e\x05\ -\xae\x06\x66\x4b\xa9\xc1\x56\x93\x82\x25\xfc\xf8\xeb\x57\xba\x76\ -\x34\xe1\xb5\x5a\x7e\x9f\x61\x34\xc8\xf3\x83\xbd\xaf\xe6\x70\x0a\ -\xf6\x55\xa0\xa5\x63\xb5\x34\xe5\x68\x24\x5f\xd6\x1d\xcc\xca\xa5\ -\x66\x60\x29\x70\x86\x45\x1d\x90\x20\x3c\x1b\x9b\x1c\x78\x5a\x56\ -\x15\xd3\x24\x69\x2a\x78\x1e\xb0\x49\xb9\x22\x81\x30\x11\xe0\x8e\ -\x1a\xcb\xb6\xae\x9a\x35\xa3\x18\x58\x83\x99\x89\xd9\x9f\x8b\x42\ -\x0c\x7a\x03\xf6\x94\x44\x3a\xb3\x3e\x86\x5b\x47\x6b\xbe\x29\x2b\ -\x97\x0e\x1c\x29\x64\xbc\x24\x82\x59\xb9\x34\x13\xf8\x1f\xc0\x39\ -\xc9\x14\x04\xd3\x11\x6d\xc2\x4f\x8f\xa5\xfc\x8e\x43\xff\x13\xca\ -\xc1\x35\x07\x0a\x4a\xec\x47\x6c\x02\x22\xd1\x60\x81\x0d\xd2\xa4\ -\xd6\xcb\x56\x74\xcd\x2c\x24\x6e\x48\xe2\xd5\x01\x3f\x6c\xf1\x2a\ -\x49\xaf\xb7\xdd\x1e\x90\x41\x42\xe9\xa4\xd1\x3c\xd5\xea\x0b\xb1\ -\x03\xd8\xfa\xb2\x09\x66\xe5\x52\x00\x56\x27\x73\x9a\x44\x77\x90\ -\x9a\x80\x1a\x78\x63\x52\xbe\x76\xf6\xf5\x3b\xb6\x1f\x52\xce\x29\ -\x5d\x20\xa9\x11\xb3\x0f\x91\x03\x0f\x02\x0b\x53\x32\x21\x28\xc7\ -\x84\xe0\xd4\x36\xd9\x59\xa3\xb5\x3c\x36\x14\xc2\x62\x39\xec\x05\ -\x6f\x36\x4a\xe0\x66\x50\x2d\xc9\x53\xb1\x9b\x12\x61\xf6\xb4\x42\ -\x38\x19\xfc\xf4\x91\x64\xbc\x94\x3b\xf8\x0e\xcc\xc9\x31\x30\x17\ -\xbc\x07\x7c\x47\x12\x9f\xa4\xa2\xf7\x76\xaf\xde\x71\xdb\xe1\xca\ -\x45\x11\x01\x0b\x0d\x4d\x9c\xf5\x30\xb0\x05\x29\x62\x57\x04\xc1\ -\xd2\xac\xc9\x0e\x3a\xe1\x86\xc1\x4c\xe6\xb6\x20\xaf\xc7\x2e\x08\ -\xee\xeb\xea\x1b\xb8\xbc\xa0\xfc\xa3\x24\x06\x64\x0e\x26\xd8\x45\ -\xa4\x9d\xf1\x8a\xe3\x05\x78\x29\x9f\xe8\xa5\x88\x36\x5b\x07\x48\ -\x5e\x51\xba\x3e\xfb\xee\x11\x95\x5b\xbb\x63\x60\x60\x59\xe7\x23\ -\x0a\x9c\x96\x92\xa7\x20\x72\xc1\x9f\x00\x77\x46\x98\x95\x08\x07\ -\xc0\xc8\x6e\xdf\xb4\x6a\x6e\xc3\x09\x2b\x37\x8e\x1e\x49\x4e\x67\ -\xc3\xc0\xda\xed\xa3\x9d\x57\x44\xab\xa9\x3a\x56\xf8\xe7\xfe\x65\ -\x9d\x1f\x0e\x66\x1e\x4e\x4f\x10\x34\x4d\x10\x64\xaa\x16\x47\x7c\ -\xfe\x45\x59\x30\x2b\x97\x16\x00\x73\xc7\xef\x9c\x7f\xde\x75\xc3\ -\xe0\xf7\x26\xfd\xb3\xed\x8a\xfd\x1d\x27\xfa\x63\xf0\x34\xc1\x4c\ -\x9b\x73\x80\x5a\x6e\xa6\x8a\xb4\x57\x38\x25\xab\x85\xe1\xe1\xd6\ -\x49\xe5\xac\x74\xad\xbb\x2f\xfb\xda\xe7\x9b\x06\xfe\xb1\x58\xac\ -\x5e\x23\xfc\x01\xa3\x57\x3b\xc4\xd3\x40\xf5\x11\x8a\x44\x76\x31\ -\x89\x05\x5f\xec\x27\x7a\x8d\xad\x46\x23\xa7\x3c\x7e\x72\xb2\xc0\ -\x7c\x08\x1b\x9a\x06\xef\xb7\xb4\x3e\x47\x31\xa1\xd6\x80\x2b\xc0\ -\x95\x41\x74\x23\xf6\x03\x49\xc1\xd3\xeb\x03\x97\x1f\xeb\xe0\xf7\ -\xed\xeb\xad\x4f\x81\xb3\x90\x5a\xc0\xb3\x84\xbb\x81\xc6\x84\xd6\ -\x1b\xed\x00\xe2\xcb\x22\x98\x95\x4b\x7f\x68\xb3\x54\x72\x77\xb2\ -\x7f\x71\x4b\xd3\xf6\xa3\x26\xb9\x00\xaf\x5f\xe9\x5a\x8e\xff\x21\ -\x98\x91\x20\x66\x80\x6c\x5c\x45\xcc\x96\x69\xb7\x74\xd0\xa6\x31\ -\x84\xf0\x86\x63\xc9\xea\xbd\x71\xcb\x41\x39\xfd\x0c\xb3\x07\x98\ -\x09\x04\xec\xf5\x4e\x3c\x12\xaa\xf9\x08\xb0\xf7\x25\x13\xcc\xca\ -\xa5\xd3\x31\x1f\x40\x9c\x88\x69\x20\xe9\xde\x95\xc7\xf9\x6c\x6d\ -\xb4\x72\x7f\x4a\x6c\x09\x4e\xd3\x92\xf8\x7d\x59\xef\xb3\x39\xcb\ -\xe8\x34\x12\xb9\xcd\x01\xe1\x79\x4f\x7f\xf8\xa4\xfa\x63\xc9\x1a\ -\x6d\x6c\xfe\x92\x0a\xfc\x8d\xf1\x46\x49\x9b\x2c\xdd\xa1\xa0\x9d\ -\x29\x86\x1c\x8e\x7c\x07\x8f\xea\x64\xb2\x72\xe9\xd5\xc0\xfb\x84\ -\x5e\x33\x11\xa4\x67\x58\x0c\x15\x22\x57\xf6\x8f\x76\x1c\xec\x82\ -\xcf\x1f\x4b\xa9\xfa\x91\xa6\x31\xea\xab\xfb\x12\x6a\x14\x14\xc7\ -\xe3\xa5\x12\xb6\x08\x74\x04\x33\xe4\xa4\x3b\xe6\xb7\x3d\x9d\x1f\ -\x4b\xd6\x84\x23\xfa\x46\x7f\xb9\x7b\xc4\x4e\x1f\x42\x2c\x8e\xce\ -\xf7\xe6\x79\x6c\xeb\xba\x61\xfb\xe6\xe3\x22\x38\x91\x2f\x5e\x02\ -\xbc\x19\x38\x55\xa6\x29\xc1\x3c\x44\xcd\xf6\xd6\x20\x0d\x27\xd1\ -\x66\xb4\x54\x92\x7c\x8c\x7b\x98\xda\xf3\x73\x63\x8a\xa7\xd8\x69\ -\xbd\xa4\x56\x3b\x35\x07\x11\x2d\x8a\x58\xb9\x48\xb5\x14\xf9\x29\ -\xc7\x48\xd7\x0e\x47\xf7\x9a\xfe\xef\x66\xcb\x3b\x4f\xc1\xbc\xce\ -\xd2\xc9\x8e\x1e\x65\x3c\xc6\x4e\x4e\x70\x22\x9f\xbb\x06\x78\x1d\ -\xd0\x22\x68\x06\x9a\x2d\xf6\x4a\xe9\x01\xe7\xba\x2b\x28\x9c\x23\ -\x79\xba\xed\xa8\x18\xbe\x7f\x2c\x72\x00\x31\xa5\x53\x21\x24\xa1\ -\x75\x92\xb7\x43\xa8\x98\x34\x1f\x34\xdd\xa4\x3d\x42\xa5\x40\x3a\ -\x6b\xb0\x5c\x1a\xec\xe8\xcb\x7e\x78\x3c\x04\x6d\x7b\xeb\xb5\xb3\ -\x3e\x57\x68\xa8\x5e\x48\x62\x7a\x08\x84\xbb\x57\xa9\x70\xa4\x9c\ -\x36\x4c\x90\x3b\x1d\xb8\xc5\xf0\x66\x89\x59\xc0\x74\x60\x4b\x6e\ -\xfa\x1a\x1a\x2a\x97\xd9\xf1\x96\x42\x48\x5b\x6b\x07\x0b\x2b\x9c\ -\xd2\xb7\x9c\xfb\xaf\xba\xae\xeb\xbf\xed\xf9\xc2\x26\xa1\xf8\x1b\ -\xc4\x01\x05\xea\x92\x19\x96\xdd\x8f\xc3\xed\xd5\x94\x5f\x99\x57\ -\xea\xae\x4c\x0a\x37\xcb\xba\x87\xe0\xc8\x35\x2a\x1e\x9f\xcc\x43\ -\x4e\xc7\x43\x09\xf2\x64\x71\xc2\xf0\xcc\xf6\x23\xfd\x2f\x64\xe5\ -\xd2\x6b\x80\xb5\x40\x8f\xa4\xba\x04\xdf\x70\x4d\x57\x94\xd6\x0c\ -\xfc\x51\xf7\x9a\xec\x9f\x5a\x57\xee\xd9\xdb\xb5\xbb\xff\x76\x4b\ -\x5b\xeb\x9a\xc7\xda\x77\x37\x76\xdc\xd2\x75\xc3\xc0\xbf\x1e\x2b\ -\x44\x1c\x42\xd7\x9a\xec\xa7\x4e\x3c\x94\x8c\xa2\xb4\x77\x4c\xfa\ -\xf7\x54\x0d\x3f\x59\xdf\xb4\x73\xb0\xf7\xc6\x2d\x07\x09\xdc\xd3\ -\x51\x3f\x78\xfb\x48\x5d\xd3\x4f\xfb\xa7\x77\xbc\xbb\x7f\x45\xcf\ -\x29\xc7\x4b\xd2\x21\x1c\x44\x4e\xd8\x6e\xa9\x4b\x47\x0c\x13\xea\ -\x5f\xde\x79\x13\xb0\x04\x34\x10\x53\xed\xa3\x33\xaf\xdf\xb1\xfe\ -\x78\x0f\x38\x5e\x64\xcb\xbb\xae\x92\x7c\x3e\x22\x4b\xb9\x1f\x0c\ -\x31\x8d\xe5\xb5\xd8\x10\x63\xe8\x52\xca\xb7\x57\xe5\x42\x50\x78\ -\x73\xc4\x83\x39\x6a\xa9\x39\x7d\x75\xd6\x9a\xc1\x7b\x26\x93\xb7\ -\x65\xd9\x9c\xee\x62\x1c\xfd\x08\xd6\x3c\x9b\x64\xf1\x8b\xb1\x86\ -\xc6\x9b\x8e\x94\x0d\x15\x18\x2f\x54\x6b\x52\xfa\x71\x1e\xe2\xc6\ -\x57\x9a\x1c\x40\x88\xe9\x8e\xdc\xe1\x4d\xb2\x3b\xa5\x70\x11\xa8\ -\x1a\xa2\xba\xa4\x34\x94\x42\x38\x2d\x26\xef\x4b\xd2\x2f\x6b\xb8\ -\x3d\x8a\x83\x05\xc2\xdb\x81\x17\x10\x7c\xe0\x1a\x15\xbb\xdb\x3a\ -\xff\x6b\x5d\xe4\x32\x5b\x07\x40\x39\x4a\xff\xc7\xd2\xe3\x93\xa5\ -\x7a\x01\xd8\x0c\x54\x9c\xf4\x7b\xc0\xa7\x76\xae\x68\x9f\xf2\x4a\ -\x92\xdb\xb9\x6c\x66\x77\x5e\x8b\x33\x20\xfd\x33\x68\x0f\x81\x21\ -\xc1\xf6\xe4\x74\x5f\x4d\xdc\x13\xe5\x6f\x2b\xf0\xb8\x53\x9e\x15\ -\xc4\x08\xe3\xad\x8f\x99\xeb\x3e\xd8\xf1\x1c\x3d\xb6\x5e\xdb\xde\ -\xdd\x3b\xa3\xf3\xfd\xb2\x97\x18\x0e\x26\x78\x06\x73\x9f\x08\x9b\ -\x7a\xea\x07\xee\x9c\xec\x7c\xf5\x2f\xef\xac\x03\x2e\x07\xde\x85\ -\x69\x57\xe0\x07\x9d\xab\xb3\x4f\xbc\x12\xe4\x06\xfe\xb2\xd4\xb1\ -\x6b\x24\x8d\x2c\xfc\xbb\xc1\x03\xab\x56\x29\xbc\x77\xac\xbd\xb3\ -\xd9\xb4\xd4\x28\x14\x48\x68\xdb\x9e\xec\xc9\x9e\xb6\x52\x6b\xca\ -\xc3\x0c\x85\xda\xd2\x80\x3a\x9c\xbc\x84\xa0\x86\xbc\x50\xfb\x5c\ -\xb1\x16\xa7\x1a\x77\x26\xc2\x6b\x10\x07\xb0\xa7\x42\xd8\x80\xd3\ -\xa8\xcd\x50\x88\xe1\x7b\xa5\xd5\xfd\x3b\x8e\xa6\xc3\xb3\x6d\xc3\ -\xac\x5c\xea\x00\xbe\x60\xbc\x57\xe8\x66\xe0\xfe\x52\x5f\x76\xdc\ -\xb1\xe9\x48\xe8\xbf\xa6\xa7\x29\xb5\x8e\xce\x28\xa4\xe2\x9e\x54\ -\x48\xe7\x07\x85\xf3\x95\xfc\x58\x47\xe3\xe0\xd7\x0f\x8f\x7b\xfd\ -\x7f\xd1\xd3\x4e\x5d\xed\x2a\x59\x8b\x24\xe6\x18\x37\xcb\x3c\x90\ -\x5b\x03\x85\xe0\x42\xb2\x2e\xc1\xde\x43\xf0\xf7\x6b\x49\x8f\x37\ -\x38\xad\x6b\x9f\xa8\x3b\x8f\x85\x67\xd3\xad\x52\x5f\x36\x08\xfc\ -\x83\x50\x3b\xe3\xd5\xfa\x87\xb3\x72\xa9\xe9\xe5\x10\xec\xba\x79\ -\xdb\x48\x08\xf5\x67\xab\xe8\x8f\xca\xf1\x5c\xcc\xab\x92\xc2\xfb\ -\x07\x46\x3b\xbf\xbc\xf3\x86\x99\x2d\xcf\x51\x24\x15\xea\x92\x18\ -\x4e\x89\xe9\x58\x4d\x98\x01\x50\x7f\x6e\x6d\x46\x8c\x22\xcd\x0f\ -\xe8\x97\xbd\x6b\x06\x7e\x78\xbc\xe4\x9e\x43\x70\x82\xe4\xed\xc0\ -\xb5\xc0\x43\xc0\x42\xe0\x8a\x89\x0a\xfe\x25\xe3\xbe\xf5\xfd\xdf\ -\xce\x53\xe1\xcb\x21\xa6\x9b\x48\x7c\x47\xa4\xd6\x64\xe6\xa6\xbd\ -\xe1\x12\x80\xcd\xe5\x39\xd3\x55\x4c\xef\x48\x4a\x4d\xd1\x9c\x9c\ -\xf0\x4e\x89\x99\x56\x58\x58\xef\xea\x43\x92\x76\x3b\xe7\xd7\x86\ -\xb1\xe1\xb1\x34\xff\xc5\x9e\xff\x82\x54\xad\xd4\x97\x3d\x99\x95\ -\x4b\x6b\x81\xff\x02\xcc\x05\xce\xe3\x08\x1e\xed\x78\x71\xc5\xff\ -\x76\xce\xb8\x23\x63\xdd\xaa\xc5\xb7\xb6\x8f\xee\x7a\x2f\xf2\x8c\ -\xe4\x70\x49\xb6\xac\x6b\x4f\x48\x38\x2f\xf8\x94\x20\x5e\x47\xe2\ -\xc4\x28\x9c\x4c\x0d\x52\x88\x63\xf9\x53\xb5\xfa\xc2\x28\x51\x11\ -\xa7\x45\x8d\x05\xcd\x7d\xb1\xe7\x1f\xd1\x3a\xa5\xbe\xac\x0a\xdc\ -\x06\xe4\xc0\x19\x59\xb9\xa4\x97\x4a\xf0\x70\x7c\x93\x47\x6b\x49\ -\x1e\x0a\xb8\x15\x98\x1f\x50\x73\x21\xfa\xb3\x11\xae\x96\x79\x95\ -\x03\x2d\x92\x0a\xd1\x3c\x15\xcc\x48\xa5\xa1\xfe\xf2\x7b\x36\x0c\ -\xac\x4b\x79\x78\xc8\xd6\x16\x42\xb8\x68\x4b\xb9\xeb\xdc\xac\x5c\ -\x5a\x90\x95\x4b\x9d\x13\x03\x9c\xa3\x62\xd2\x6a\xa2\xd4\x97\x0d\ -\x65\xe5\xd2\x6f\x80\xd3\x81\x79\xc0\xf1\x25\x00\xab\x14\xb2\xb1\ -\xd2\xa5\x88\x13\xa9\xd5\x36\x2a\x8f\x77\x77\xae\xcd\x86\x01\xde\ -\xb2\x9d\xe8\x19\xd4\x29\x50\x55\xf2\xfc\x14\x7d\xab\xd2\x78\x8f\ -\xcd\x46\x18\x13\x5c\x25\x50\x67\x13\xaa\xb9\x8b\x8b\x20\x46\xf2\ -\xee\x04\xb3\x04\x0d\x05\xa7\x3f\x46\xfa\x36\x70\x12\x30\x3d\x2b\ -\x97\x76\x00\x4f\x96\xfa\xb2\x23\xc6\xf0\xa3\x0e\x5f\xb2\x72\xa9\ -\xc4\x78\x02\x9e\x03\xf7\x02\x3f\x3b\x9a\x67\xdd\xb4\x6a\x6e\x43\ -\xfd\xe8\xc1\xcf\x0a\x9f\x85\xd5\xe2\xe0\x21\xac\xbb\xbb\x76\x0f\ -\xfc\x25\x37\xbb\x0a\xd0\xbf\xa2\xfb\x9d\x72\x7e\x1d\xd2\x0c\xcc\ -\x01\xc3\x1e\xf0\x6e\x89\x26\x5b\xf3\x03\x4c\x45\xec\x37\xba\xdf\ -\xf6\xbd\x4a\x69\x63\x90\x76\x27\xf1\x76\x9b\x29\x79\x08\x85\x50\ -\xad\x7e\x46\xa1\xae\x26\x6c\x93\x3a\x08\xb4\x0a\xed\x07\xee\x2a\ -\xf5\x65\xfb\x8f\x9b\xe0\x04\xc9\xb9\xc0\x1f\x02\xd3\x26\x88\x66\ -\xc0\x26\xe0\xc1\x52\x5f\xb6\x13\xe0\x9b\xef\x50\x7c\xed\xfc\x9e\ -\xd6\x90\xd2\x3b\xa4\xfc\xed\x58\x84\xa0\x19\xc9\x6e\x33\x7e\x66\ -\x9f\x0e\xbe\xed\x94\xd5\x43\xbb\x00\xb2\x15\x5d\x97\x27\x6a\xcd\ -\x58\x67\x43\x78\x24\xc9\x23\xf5\x56\x4b\x2d\xf1\x16\x45\x5e\x87\ -\x69\x35\x3c\x10\xe5\xc7\x73\x34\xc5\x79\x7a\x98\xa8\x07\x81\x73\ -\x22\x3a\xb1\x96\x73\x77\x2c\xb8\xc5\xb9\x6a\x88\x42\x4a\xc4\x10\ -\x43\xbf\x49\xd5\x60\xa6\x01\xdf\x2e\xf5\x65\x03\x87\xf4\x3f\xa6\ -\x87\x9c\x30\xfd\xa7\x81\xaf\x4d\x58\x71\x27\x70\x2a\xf0\xa1\xac\ -\x5c\xba\x18\x49\x17\xcc\xe9\x6c\xe8\x59\xbd\x75\x57\x54\xca\x41\ -\x4f\x48\x3c\x52\x23\xdd\x82\xfd\x68\x90\xc6\x4e\x99\x39\xed\xd9\ -\x21\x89\x82\x23\x91\x87\x2b\x41\x6b\xbb\xfb\xb2\xaf\x14\xad\x37\ -\xe6\x70\xa6\xc4\x6b\x31\x75\xe0\xed\x63\x79\xfe\xdf\xf2\xdc\x77\ -\x84\x44\x3f\x0a\x9d\xc1\x7a\xab\xf0\xa9\x09\x4e\x8f\x81\xf7\x3a\ -\xd7\xf9\x36\xe7\x02\x4b\x62\x74\x83\xc9\x67\x04\xeb\xa4\x04\xbb\ -\x81\x77\x1d\xde\xca\x7f\xc9\xf3\xc1\xac\x5c\xea\x32\xfa\x3c\x62\ -\x4a\x44\x29\xe6\x63\x1f\x1e\x75\xb1\x37\x04\xbf\x49\xd6\x43\x39\ -\xae\x2f\x16\xfc\x8b\x94\xc2\x05\xa5\xbe\xfe\xcf\x1d\x7a\x6e\x47\ -\x79\xd6\xfc\x51\x57\xba\xa3\x55\x8f\xd4\x10\xd0\xc7\x08\x9e\x83\ -\x3d\x05\x34\x94\xf0\xdf\xe4\x39\x77\xd7\x45\xbd\xaf\x92\xb8\xbb\ -\x10\xf8\x5f\x41\x2a\x62\xf7\x22\xc6\x82\x7d\x67\x22\x8c\x49\x3e\ -\x91\xe4\x61\xd0\x8e\x14\xc0\xf0\x48\xb0\x3a\x80\x27\xc0\xd3\x81\ -\x9b\x4a\x7d\x59\xfe\x92\x63\x5c\xa9\x2f\xeb\x17\x64\x4a\x5e\x5a\ -\x4b\xa9\x75\x2c\xd4\xbd\x29\x44\x5f\x16\xa3\xbf\x12\xa2\x1a\x63\ -\x54\x1c\x2a\x0d\x3e\xb1\x6d\x77\x76\xf3\xe1\xcf\x0d\x37\x14\xb6\ -\xd6\x85\x70\x09\x31\x9c\x17\xc5\xd5\x92\x17\x60\x9a\x80\x7e\x9b\ -\xcf\xc6\x9a\xbe\x5e\x2c\x84\xb7\x13\x78\xb8\xbe\x48\xa3\xcc\x53\ -\x38\x09\xa9\x1e\x53\xcc\x09\x67\x01\x73\x30\xdd\x49\x92\xc5\x6e\ -\x41\x21\xd8\x8b\x4c\xbe\x3f\x25\x16\x30\xee\x3c\x2f\x82\x97\x39\ -\x5d\x32\xf9\xb7\x08\xaa\x05\xa9\x19\xd2\x42\xc4\x63\x1d\xd7\x0d\ -\x3c\xfc\xd3\xa7\xfb\xff\xb1\xe8\xea\xfd\xf3\xff\xbb\x2b\xaf\x99\ -\x70\x2e\x87\xd0\x52\xdd\xdf\x46\x4e\x29\xe2\x05\x86\x53\x13\x0e\ -\x36\x1b\x51\xf8\x42\x57\xe3\xc0\xa7\x54\xe0\x5c\x4c\x53\x35\xe7\ -\xd1\x50\xf4\x8f\x10\xd1\x8a\x7b\x6c\x57\x10\x23\xc2\x6d\xc8\xe7\ -\x1b\x92\xc4\x62\xe0\x02\x27\x7a\x85\xa3\xd0\x6c\x05\x55\xac\x60\ -\xe0\x82\xac\x5c\x2a\x1c\xb3\xb3\x2d\x49\x5b\x3f\xd6\xd3\x13\x8a\ -\x29\x0e\x17\x2b\x7b\xe6\x3f\xba\x7b\x98\xf1\xe0\x0d\xd5\xe2\xaf\ -\x54\xcc\x6f\xcd\x61\x6e\x84\x5f\x74\xae\xce\xbe\xb8\x6a\x95\xc2\ -\xfb\xe7\x76\x9e\xd1\xb6\x7e\xe0\xfe\x23\xc9\x6b\x2b\xee\xea\x1f\ -\x48\x9d\xcd\xc9\x2c\xc6\x6e\x0f\x31\xfc\x7a\x84\xb4\x7a\xee\x75\ -\xd9\x4f\x90\x54\x5b\xae\xf3\x65\x7a\x6a\x95\xca\x96\xde\x35\x7b\ -\x0e\x64\xcb\xbb\x1e\x93\x52\x4a\x49\x53\x89\xde\x86\xb5\x74\x7c\ -\x6a\xc3\xc9\x58\x96\xdd\x86\xd8\x9f\xac\x7d\x22\x3c\x92\xec\xa9\ -\x41\x6e\x43\xec\x03\x4e\x3b\xea\x1d\xdc\xb9\x6c\x66\x77\x85\xc2\ -\xbc\x10\xd2\xc5\xa0\x0b\x64\x92\xa1\x1a\xe4\xfd\x79\x5e\xb8\x3d\ -\x3a\xff\x4e\xe7\xda\x6c\x78\xcf\xf2\x19\xd3\x86\xf3\xe2\x9c\xda\ -\x94\xa6\x27\x1b\x2b\x07\x7f\x6f\xff\x81\xea\x3d\xf3\x3f\xb3\x6b\ -\xd2\xb1\xd8\x86\xe5\x33\xa6\x35\x52\x77\xb9\xd0\xdc\x24\x6f\x6c\ -\xd1\xc8\x9d\x2d\xab\x87\x76\x6d\xf9\x58\xe7\xbc\xba\xa8\xcf\x21\ -\xef\x2b\xf5\x0d\xbe\xe7\xd1\xbf\x5e\x54\x6c\x1b\xdb\x79\xbe\x93\ -\xcf\x93\xa8\x92\x58\xe4\xa0\x67\x9c\xfc\x47\xd2\x44\x56\x63\x2a\ -\x12\x03\xc4\xfc\x5a\xe7\xe1\x4d\x0a\x54\x53\xa2\xaa\xf1\x66\x70\ -\x65\x52\x82\x83\x1f\xef\x5c\x9c\xac\xab\x95\xf4\x96\x84\xa7\x49\ -\xd4\xd9\x4a\x92\x13\x22\x61\x2a\x82\x4d\x39\xe9\xcb\x8c\x71\x9f\ -\x1a\x8a\x2d\xd5\x34\xbc\x71\xc7\xee\x7d\x07\x9e\xff\x59\x4e\x86\ -\xac\xdc\xf5\x3e\xe3\x86\x90\xf2\xf5\x11\x7e\x56\x71\x7c\x43\x8c\ -\x2a\x1b\xaf\xef\xea\xcb\xde\xd3\xbf\xa2\xe7\x94\x3d\xfb\xaa\x5b\ -\x5b\x5b\xc2\x1b\x82\xb4\x44\xd1\x0f\x8c\x56\xf8\x4d\x43\xc1\x5f\ -\xc5\x3a\x15\xdc\x6c\x8d\x0f\x19\x8d\x7e\x8d\xfd\x2b\xa3\x2c\xc4\ -\x34\x1d\x87\x3d\x36\x2d\x2f\xbc\x83\xab\x14\xb6\xaf\xe8\x7a\x63\ -\x35\xf9\x7a\x27\xde\x6b\xa5\x2e\x89\x00\x0c\x23\xf7\x83\x06\x30\ -\x15\xa3\x16\xc3\xb9\x81\x78\x65\xa8\x8b\xd7\x85\x3c\x5d\x56\x6c\ -\x68\x7e\xc1\x9d\x3b\x1a\x62\x43\xfe\x0d\x9b\x83\x63\x2e\x0c\x54\ -\x89\xaf\x8d\x41\xf3\xc1\x8d\x1a\x1f\xc9\x41\x6d\xac\x69\xe1\xdf\ -\x0d\x1e\x18\x6b\x6c\xbc\x43\x78\x5f\x9e\xbc\xb4\xbe\xa0\x3f\x06\ -\x1d\x44\x1e\x35\x8c\x81\xf2\x24\x6d\x03\x7a\x09\x74\x46\x3c\x52\ -\x4b\x51\x46\xd3\x81\x69\x2f\xb0\x60\xb6\xa2\xeb\x8d\xd8\x1f\xc5\ -\x9c\xa5\x40\x1c\x77\x00\x3c\x9e\x8c\x35\x3e\xaa\xde\x8d\xc2\x0c\ -\xe0\x02\x2b\x95\x90\x12\x89\xcd\xd8\x3f\x1c\xab\xa4\x55\x51\x0d\ -\x7b\x7b\x6f\xdc\x72\xf0\x39\x42\xaf\x51\x71\xc7\x8c\x99\x73\x6c\ -\x35\x1f\xa0\xba\x29\xc6\xd8\x14\xc6\x42\x63\x21\xea\x62\xc1\x69\ -\x0a\xb4\x62\x3f\x91\x1c\xa6\x49\x7e\x2b\xd0\x1f\x43\x7a\x77\x2d\ -\x15\x7a\x92\xc2\xa6\x9e\xd5\x5b\x77\x0d\xfc\x65\x69\x6e\x2a\xf0\ -\x91\x00\x1d\x8c\x0f\x72\x16\x11\x68\xb3\xb1\xe4\x6d\x29\xd7\x9f\ -\x87\xe8\x05\xe3\xab\x1d\xb1\x5b\x4e\x4d\x16\x8d\xcf\xb1\xe0\xd6\ -\x6b\x67\x35\x42\xba\x0c\x38\x1b\x51\x48\xf6\x86\x64\xdd\x6a\x33\ -\xe4\x9a\x3f\xdd\xd5\x97\xbd\xa7\xb4\x66\xe0\x43\x12\x55\x4c\x9b\ -\x1c\x64\xfb\x4e\xa1\x51\x49\x17\x35\x4e\x09\x8b\xeb\xea\xc6\xde\ -\xfe\xc4\xb2\xf6\x16\x80\xbb\x57\xa9\x90\x2d\xeb\x3a\x2b\x6b\xed\ -\xb8\xa6\x4a\x78\x67\x1e\x74\x69\x93\xea\xca\x85\xbc\xbe\x3d\xd4\ -\xa9\x57\x84\x0d\x29\xf7\xf7\xc6\x12\xdf\x4d\xa6\x92\xa4\x0d\xc8\ -\x8d\xa0\x98\x5b\x6f\xce\x6b\x79\xb5\x98\xe8\x05\xe8\x5c\x9b\x6d\ -\x8c\xc1\xdf\xc7\x34\xda\x6a\x00\x8a\x98\xaa\xcc\x5e\x27\x4d\x0d\ -\x45\x65\x42\x05\x49\xb9\x02\xd1\x92\xe1\x79\x61\xa2\xae\x69\xec\ -\xf5\xa4\x70\xb1\x51\x00\x8d\x58\xe1\xd3\x21\x78\x76\x95\xd1\x8f\ -\xf5\xac\x1d\xf8\x39\x40\xff\xf2\x9e\xd9\xd8\x17\x21\x0a\xe0\xbd\ -\xaa\xf9\x73\xd8\x4f\x63\x3d\x43\x1e\x96\xe4\x78\xf3\xd4\x50\xf8\ -\x83\x6d\x2b\x66\x2e\x98\x5f\xeb\x3d\x41\x05\x5f\x40\x08\x53\xb1\ -\x23\xe4\x07\x30\xc3\x15\xd2\xde\x9e\xeb\xb2\x7b\x4a\x6b\xb6\xff\ -\xb8\x7b\xed\xc0\x1d\x75\x39\xdf\xc3\xf1\x7b\xf5\xaa\xfe\xc8\x49\ -\x35\x43\xab\x92\x2e\x54\xa8\xed\xce\x43\x75\xee\xf8\x8b\x87\xbf\ -\xaf\x1b\xbc\x4b\xf2\xdf\x23\xea\x11\xdb\x11\x07\x08\x8c\x22\xf6\ -\xa4\x8a\xa7\x26\xab\x29\x4a\x2d\x76\x5e\xb1\x5d\x07\x1c\x7c\x96\ -\xe0\xba\x55\xaa\x73\xf2\x6b\x91\x4f\x08\xb6\x30\x9b\xa8\x79\x54\ -\x55\x3e\x35\xbb\x6f\xef\x1e\x80\x6d\x2b\xa6\xb6\xc5\x50\x5b\x6e\ -\x68\x04\x57\x4d\xba\x35\x84\x30\x2b\x37\xb7\xa1\xf4\x60\x4a\xf9\ -\x8e\x91\x3c\x3c\x1e\x60\x28\xa6\xf0\x36\x57\xf2\x8e\x90\xd2\xb7\ -\x8c\x47\x42\x08\xeb\x55\xd3\x16\xa7\xf0\xc0\xbc\x35\xdb\xb7\x1c\ -\xfe\x62\x3b\xd7\x66\xc3\x5d\xd7\x6f\x7f\xec\xb6\x5d\x3b\x37\x49\ -\xde\x21\xe8\xcc\xd1\xec\x10\xea\x2f\x91\xd3\xde\x62\xb1\x7a\x3a\ -\xc0\xca\x95\x4e\x9d\x6b\x06\xef\x92\x7d\x3b\x68\xb7\x93\xf7\x56\ -\x53\xb8\x2a\xd4\x58\xe2\xa2\xbb\x48\xf9\x60\x35\xb9\x35\x25\xea\ -\x25\x9a\x80\xf5\xcf\x12\x9c\xbe\xbf\x7b\x6a\xb2\xe6\x8e\x8f\x95\ -\xc9\x8d\x1f\x51\x81\x29\x9d\x9f\x18\xd8\x04\xb0\x79\x45\xd7\xc2\ -\x90\x9a\xbf\x90\xac\xd3\x25\x57\x80\x27\x9d\x42\xb3\x9d\xba\x8a\ -\xb0\x3b\x21\xa3\xd8\xdc\x10\x99\x5f\xe7\xb1\x9f\x26\xf8\x49\x5d\ -\x48\x57\xe7\x79\x3c\xc3\x35\x1e\x53\xf2\xe2\x10\x35\xed\x0b\xcd\ -\xfd\x3f\x98\xcc\xe9\xfc\xe9\xcd\xae\x26\xfb\x5e\xec\x5a\x90\xbb\ -\x64\xbf\xbb\x96\x0a\x43\x0a\xa1\x67\xdb\x8a\x99\x0b\x60\xbc\x6d\ -\xbf\xab\xb1\xfd\x06\xe1\x87\x14\xf8\xf1\xac\xeb\xfb\xef\x4d\x75\ -\xf9\xc9\x21\xb1\x80\x58\xa8\x33\x0e\xa0\xb9\x8c\x2f\x1f\xdd\xf3\ -\x6c\xa0\xb7\x69\x0c\xd0\x69\x90\xe4\x31\x59\x8f\x60\x7c\xa8\x83\ -\x5d\x2f\xbf\xc7\xa2\xce\xe6\x51\xa1\x01\x9b\x47\x63\x64\x63\x72\ -\x78\x4f\xc2\x43\x32\x77\x2a\x31\x12\x0b\xbc\x79\xfa\xea\xdd\xff\ -\xbe\x7f\x79\x67\x94\xd8\x9a\xab\xb6\xbd\xe8\xf8\x54\x8d\x9a\xc9\ -\xb5\x61\xe5\x4a\x1f\x75\xfd\x4a\xf8\xeb\x48\x17\x80\x4b\xc6\x14\ -\x03\xab\x2b\xc9\x9f\x8a\x21\xbe\x26\xfb\x78\x57\x4f\xed\x60\xe1\ -\xa1\x85\x37\x6e\xd9\xbd\x4a\xba\xf6\xcf\xfe\xa2\xb3\x7d\xe0\xe3\ -\x9d\x6f\x51\xee\xb3\xab\xf6\x8e\x42\xca\x4f\x29\x10\x50\x48\x0d\ -\xb6\x06\x81\xfb\x0b\x30\xbe\xda\xe8\xfa\xbc\x91\x54\x68\x42\x96\ -\xad\x31\x89\x41\x2b\x3d\xeb\xf2\x83\xd3\x53\xc9\xc1\x0a\x7c\x37\ -\x4f\x5c\x68\xf9\x31\x1c\xce\x34\xfc\x8b\x82\xfe\xb5\x6b\x75\xb6\ -\x73\x70\x79\xc7\xe5\x36\xbd\x5b\x3f\xde\xd6\x3d\x7b\xcd\xae\x9f\ -\x3f\xf6\xe7\x33\x37\x9e\xfa\xb7\x3b\x07\x26\x5e\xd2\xa4\xbd\xcb\ -\xe7\x10\x54\x5c\x87\xfd\x6b\xc4\xa5\x12\xf3\x2c\x3d\x5a\x27\x7f\ -\xc4\xe8\x71\xf2\x7c\x5d\xb1\xc1\xf3\xfa\xcb\x25\x7d\x60\x79\x67\ -\x48\xa4\x36\xf2\x38\x5d\x49\xbb\x8b\x31\x9d\x38\xbe\x54\xe5\x45\ -\xb6\x6a\xc0\x17\x4b\x7d\x59\x3a\xf4\x89\xb6\x16\x52\xac\xb7\x52\ -\x2e\x10\xe3\x86\x3b\x49\x29\x54\x0e\x1d\x5c\x43\xfb\x2d\x8f\x8d\ -\xc8\x9b\xba\xd7\x64\x37\xf4\xf4\x0d\xfc\x9b\xaa\x63\x5f\x6f\x0d\ -\xb5\xef\x1c\xd8\x3f\x65\x68\xe7\xc7\xda\xa7\xd4\x92\xba\x92\x99\ -\x59\xc8\x8b\x8b\x00\x4e\xfd\xd4\x8e\xec\x78\x67\x18\x87\x50\xea\ -\xcb\x0e\x3a\xe8\x4b\x46\xeb\x8c\x1a\x6d\x16\x58\x54\x82\xd3\x81\ -\x44\x58\x62\x73\x5e\x40\xaf\xce\x43\x58\x68\x34\x35\xcf\xf3\xdd\ -\xb9\x78\x15\x68\x8a\xf0\x62\x4c\x11\xf8\x51\xa9\x2f\xbb\x1b\xfe\ -\xc3\x8b\xe6\x91\xda\xa0\x50\x05\xb0\x08\x4d\x09\x16\x4a\x1c\x64\ -\x95\x02\x8c\x0f\xc0\xab\x29\x7d\x69\xee\x75\x03\xcf\x16\x93\xa5\ -\x4f\xec\x5a\xd7\x74\xdd\x8e\xfe\xf9\x9f\x79\xaa\x52\x2d\x16\x67\ -\x84\xa8\xd6\x20\x4d\x57\xf0\xec\x17\x43\xea\xf9\xe8\x5a\xdd\xff\ -\x4b\xc9\x37\x0a\x3f\x14\x70\x8b\x60\x49\x42\x97\x45\xe8\xb4\xb5\ -\xcf\x30\xa4\x64\xe4\x30\x3f\xc4\x70\xb1\xa0\x11\xb3\xd4\x56\x13\ -\xe3\x35\xeb\x0d\x87\x64\x85\x89\xb7\xb6\xb7\xa6\x42\x30\x6c\x36\ -\xae\x80\xeb\xa3\xd4\x3b\x9c\xf2\x2d\x9b\x47\x3b\x4f\x00\xe8\x58\ -\x3d\x70\xdb\xac\x49\xfa\x91\xdb\x56\xf4\xb6\x15\x5d\x6d\x53\xf2\ -\x49\xe0\x36\x5b\x2f\xbb\x49\x55\x5a\x9d\xfd\xb0\x86\x97\x19\xff\ -\xc2\x22\x47\xf4\x58\x2c\x15\xbe\x4c\xf8\xf7\x81\x0b\x24\xcf\x15\ -\xea\x95\xbc\x18\x18\x06\xfe\x09\x28\x1f\xbe\xd2\x75\x78\x1c\x14\ -\xf8\x4e\xa3\x21\x43\x34\x6e\x6b\x08\xf1\xfd\x4d\x21\x3f\xb8\x77\ -\xd5\xf4\xc9\xd7\x3c\x00\xe5\x95\xf6\x5a\x0a\xa7\x26\x71\x51\x72\ -\x18\x61\xbc\xea\x7f\xd9\xe8\xed\x1b\x78\x04\x74\xa5\xad\x65\xc0\ -\xfd\xc0\x01\x44\xd1\xd0\x0c\x6e\x35\x4c\x05\xef\x00\xbe\x01\x5c\ -\x5d\xea\xcb\xfe\xf6\xf9\x3d\xa3\xc3\xcb\xa5\x98\x57\x79\xb0\x58\ -\x60\xbb\xa1\x0d\x71\x82\xe0\xbc\xd1\x3c\x6c\x8f\xfb\x9b\x6e\xbd\ -\xeb\x1d\x8a\x57\x1c\x2a\x93\x0e\xc3\xf6\x72\xc7\x92\x10\xd5\x65\ -\xeb\x2d\x41\x4c\x37\xee\x07\x1e\x7d\x25\x08\x02\x94\xfa\xb2\x11\ -\xe0\x5f\xb2\x72\xe9\xdb\x40\xef\xc4\x6f\x06\x50\x05\xb6\x03\x1b\ -\x8f\xb6\x9c\x7e\xf8\x6c\xa2\x0e\xf8\x03\xac\x56\x05\xff\x4f\x9b\ -\x76\x83\x80\x87\x84\xbe\x55\xb3\xbf\xdf\xdb\x38\xf0\xd8\xa1\x99\ -\xc2\xba\x0f\x76\x4c\x69\x9d\xa6\xd3\xab\x39\x27\xd4\x45\x5d\x4a\ -\xf2\x65\x01\xed\xb5\xf8\x49\xa9\x2f\xfb\xd3\x57\x8a\xe0\xcb\xc5\ -\x73\x92\xed\xac\x5c\xea\x49\xf6\x85\x41\x9c\x25\xe9\x5d\xc9\x9a\ -\x12\x70\xb4\x3c\xe0\xe4\x5f\xa1\xc2\x6f\x52\xca\x37\xc5\xe0\x69\ -\x4a\xb1\xd5\x4a\x6d\x04\xde\x80\x35\x1b\x74\x00\xbc\x0e\x58\x59\ -\xea\xcb\xee\xfb\xdd\x51\x7a\x2e\x5e\x58\x4d\x94\x4b\xe7\x58\xe9\ -\x04\x55\xc3\x49\x14\xf4\x01\xf0\xb4\xf1\xeb\x99\xb0\x34\x2a\x31\ -\x24\x13\x2d\x17\x65\x6c\xc2\x54\xdb\x23\x82\xc7\x10\x5f\x2c\xf5\ -\x65\xb7\xfe\x8e\xb8\x1c\x11\x47\x2c\x78\xb3\x72\xe9\x4c\x60\x91\ -\xa3\xf7\x85\x1a\xef\xb7\xb4\x14\xd4\x0c\x0e\x40\x62\x7c\x53\xd3\ -\x36\xb5\x10\xd8\x95\xcc\x33\xc0\x37\x4b\x7d\xd9\x31\xf7\x66\x7e\ -\xdb\x98\xb4\xa2\xcf\xca\xa5\x6e\xe0\x0a\xd9\x63\x39\xda\x29\x31\ -\x2b\xe0\xb3\x20\xcc\x71\xca\xe5\x10\x76\x19\x17\x02\xda\x07\xac\ -\x29\xf5\x65\xff\xf7\xb7\xaa\xf9\x71\xe2\x78\x3a\xdb\x73\x80\x4b\ -\x19\x9f\x34\x75\x32\x1e\x5a\xcc\xf8\x76\xed\x5d\x8c\xb7\xf3\x8f\ -\xb9\xa5\xf4\xbb\xc2\xff\x03\xbe\xbc\xa7\xb1\x5d\x72\x52\xfb\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x05\xdc\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x05\x59\x49\x44\ -\x41\x54\x58\x85\xc5\x96\x7d\x88\x14\x65\x1c\xc7\x7f\xcf\x33\xb3\ -\xb3\x33\x3b\xbb\xb3\xef\xde\xe9\xbe\x1c\xa6\x69\x92\x52\x84\x89\ -\x60\xa9\x89\x65\x05\x52\x84\x82\x68\x6f\x9a\x78\x7f\x6c\xfd\x51\ -\x41\x7f\x04\x45\x04\x41\x14\xd2\x5f\x9b\x70\xa4\x24\x04\xda\x0b\ -\x8a\x51\x94\x85\x51\x60\xfd\xe3\x65\x45\xa7\x5e\x7a\x68\x77\xb7\ -\x73\xb7\xeb\xdd\xde\xcc\xce\xee\xde\xbc\xec\x3c\xcf\xd3\x1f\xdd\ -\x9d\x73\xdd\xde\x8b\xde\x49\x3f\x18\x66\x78\x7e\x2f\xdf\xcf\xfc\ -\x7e\xc3\x33\x0f\x02\x80\xc5\x00\x50\x87\xff\xc7\x64\x1e\x00\xea\ -\x8c\x31\x23\x97\xcb\x05\x09\x21\xf7\x21\x84\xf0\xed\x54\x64\x8c\ -\x51\x8e\xe3\xce\xe7\xf3\xf9\x1a\x42\x08\xf8\x71\x47\x80\xd2\xaf\ -\xdb\x77\xef\x8e\x0b\x92\xc4\xcf\x54\x60\xbe\x66\x56\xab\x76\xc7\ -\xf1\xe3\x43\x00\xb0\x15\x00\x6e\x00\xac\x59\xb9\x52\x59\x4e\x69\ -\x0f\x1c\x3c\x78\xf6\x76\x08\x7f\x3b\x38\x98\x7c\xe7\xe2\xc5\x8d\ -\x1d\xf9\x7c\x63\x79\x36\xab\x8c\xaf\x4f\x00\x20\x84\x00\x0c\xa3\ -\x06\x5d\x5d\xc6\x42\x89\x6a\x84\xf0\x7b\x55\x75\xeb\x99\x7a\x7d\ -\x73\x83\x31\xff\x26\x59\xfe\x71\x55\x22\x61\xff\xd4\xd3\x93\x9e\ -\x02\xb0\x90\x56\x26\xc4\xf7\xe0\xb5\x6b\xfb\xae\x39\xce\x0a\x8b\ -\xb1\x20\x00\x40\x92\xe7\x0b\xa7\xdb\xda\x4e\x01\xc0\xa3\xde\xd8\ -\xdb\xf2\xc1\x29\x18\xbb\x2d\x3c\x3f\x6c\x33\x26\x03\x00\x0b\x62\ -\xac\xff\xbc\x74\xe9\xc1\x66\xb1\x0b\xde\x81\x0b\xb6\x2d\x3f\xd9\ -\xd7\xb7\xaf\xc7\x71\x56\x87\x39\x6e\xc8\x61\x4c\x7c\x6b\xd1\xa2\ -\xc3\x77\x0a\xc2\x68\xb3\xf8\x05\xed\xc0\xa1\x91\x91\x3b\xd6\x5f\ -\xbd\xfa\x46\x8f\xe3\xac\x5e\xe5\xf7\x9f\x3f\xd3\xd6\xf6\xde\xc3\ -\xb2\x7c\xe6\xd5\x78\xfc\xf2\x74\x39\x0b\xd6\x81\x9d\xfd\xfd\x5b\ -\x4f\x18\xc6\x53\x00\xc0\x76\x85\xc3\x9f\x1e\x4b\xa7\x7f\x18\xa5\ -\x14\x9f\xca\x66\xbf\x99\x29\x6f\xde\x00\x57\x1c\x27\xb0\xbd\xaf\ -\xef\xb9\xbf\x6c\xfb\x5e\x05\xe3\xf2\xfb\xad\xad\x1d\x07\xa2\xd1\ -\xbf\x01\x00\x02\x18\xd3\xd9\xf2\xe7\x05\x70\x44\xd3\xda\x5e\x2e\ -\x16\x0f\x18\x94\x26\x56\x08\xc2\x1f\x5f\x66\xb3\x1f\xaf\xf4\xfb\ -\x9b\xce\x7a\xc1\x01\x9e\x2e\x14\x36\x1f\xab\x54\x76\x02\x00\xde\ -\xa1\x28\x5f\x7c\x9e\xc9\x7c\x7f\x2b\x75\x6e\x1a\xa0\xaf\xd1\x10\ -\x1f\xef\xed\x7d\xe6\x82\x6d\xaf\x0d\x62\xac\xbd\xdb\xd2\xd2\x91\ -\x8b\xc5\xae\xde\x8a\xf8\x4d\x03\x7c\xa2\xeb\xe9\x97\x8a\xc5\x76\ -\x9d\x90\x45\xcb\x04\xa1\xeb\x54\x36\x7b\xe4\x6e\xbf\x7f\x5e\x7f\ -\xd2\x59\x01\x6a\x94\x72\x41\x8c\xc9\x0b\xaa\xfa\xc0\xd1\x4a\x65\ -\x17\x65\x8c\x7b\x22\x14\x3a\x79\x22\x9b\x3d\x8d\x01\xd8\x7c\xc4\ -\x67\x05\xd8\x53\x28\x3c\xf4\x7c\x24\xf2\xe7\x6b\xa5\xd2\xf6\xdf\ -\x2d\x6b\xbd\x8c\xb1\xfe\x76\x4b\xcb\x47\xaf\xc4\xe3\x57\xe6\x2b\ -\x3c\x2b\xc0\x51\x5d\xcf\x9c\x30\x8c\xed\xa7\x6b\xb5\x4d\x65\x42\ -\x16\x2f\x15\x84\x4b\x27\x33\x99\xc3\xf7\x88\x62\x75\xa1\xc4\x27\ -\x01\x58\xb6\x8d\x2f\xab\xaa\xa4\x9b\x66\xb8\x42\x88\xef\xc5\xc1\ -\xc1\x9c\xcd\x58\xc0\x26\x24\xb0\x56\x92\xce\x7e\xd0\xda\xfa\x95\ -\xcb\x18\xfa\xcd\xb2\x42\x00\x37\xb6\x50\xef\x18\x30\x42\x6c\x06\ -\x1f\x00\x00\x44\x74\xdd\x47\x29\x45\x53\x00\x6c\xdb\xc6\x3d\xf5\ -\x7a\x60\xc0\xb2\x22\xaf\x5f\xbf\xfe\x6c\x8d\xd2\x28\x00\x80\x80\ -\x90\x59\x74\xdd\x96\x73\xa6\x99\x88\x71\x9c\x05\x00\x30\x91\xed\ -\x11\x41\x63\x02\x93\x44\xff\xe3\x03\x00\xc8\x0c\x0c\x88\x0d\xd7\ -\x9d\x0a\x60\x39\x0e\xee\x1d\x1e\x96\x0e\x6b\xda\x26\x9d\x90\xa4\ -\x88\x50\x6d\xb9\x20\x74\x6f\x0b\x85\x7e\x15\x11\x72\xcb\x84\x48\ -\x23\x84\x48\x63\x00\xcc\x7b\xf7\x42\x8d\x77\xc1\x0b\xe9\x8d\x77\ -\x07\x07\x25\xd7\x43\xe4\xed\x00\x1a\x18\x19\x69\x19\xe1\x79\xf1\ -\xb1\x4c\xe6\x97\xc5\x81\x80\x81\x00\xa0\x0e\xd0\x3a\x3a\x56\xd4\ -\x5b\x18\x35\x5b\xbb\xf1\xc6\xd3\xc6\x4b\xa6\x19\x69\xf8\x7c\xce\ -\x14\x00\xb5\x54\x2a\xd9\x00\x77\x6d\xdc\xb6\x8d\x07\x80\x35\x96\ -\xa7\x75\xe3\xc9\x08\x21\x60\x00\x80\x18\x43\x13\x2f\xe1\xf1\x4d\ -\x88\x8e\xe7\x35\x19\x41\xbf\xae\xdb\x0c\xe3\x4b\x53\x00\x88\x28\ -\x3e\x62\x13\x72\x7f\xb1\x58\x8c\xc1\x34\x86\x10\x62\xc9\x64\x72\ -\x8f\x24\x49\x1b\x01\x21\xe2\xf5\x31\x00\xb0\x2c\xab\xab\x54\x2a\ -\x7d\x38\x53\x7e\x3a\x9d\x2e\xfb\x38\xee\xbc\xb7\x43\x0a\x63\x6c\ -\x4e\xe7\xc0\xfd\xfb\xf7\xc7\x42\xa1\xd0\xd9\x64\x32\x19\x6c\xe6\ -\x1f\x1a\x1a\xd2\x1c\xc7\xd9\x90\xcf\xe7\x6b\x73\xa9\x87\x10\x52\ -\xe6\x7c\x20\xc9\xe5\x72\x3b\x02\x81\xc0\x77\xb1\x58\x2c\x3c\x5d\ -\x4c\x24\x12\x49\x00\xc0\x67\xed\xed\xed\xcb\xe6\x5a\x77\xc6\x0e\ -\xec\xdd\xbb\x37\x22\x8a\xe2\x21\x00\xd8\x80\x10\x0a\x8b\xa2\x38\ -\x30\x5b\x41\x42\x88\xdf\xb2\xac\x2c\x42\x48\x03\x80\x4e\x4a\xe9\ -\x9b\x1d\x1d\x1d\xe7\x9a\x8a\x23\xa4\x4c\x0b\x50\x2a\x95\xb8\xce\ -\xce\x4e\xbe\xbb\xbb\x5b\x11\x45\xd1\x45\x08\x11\x4d\xd3\xb8\x4a\ -\xa5\x82\x6b\xb5\x1a\x36\x4d\x13\xb9\xae\x0b\x00\x80\x38\x8e\x63\ -\xa2\x28\x32\x59\x96\xa9\xa2\x28\x34\x1a\x8d\x52\x49\x92\x50\xb9\ -\x5c\xf6\x2d\x59\xb2\xc4\xdc\xb2\x65\x8b\x99\x4e\xa7\x49\x33\x80\ -\x89\x8f\xd0\x34\x4d\x54\x28\x14\x78\x55\x55\x39\x55\x55\xf9\xb1\ -\x67\xbe\x50\x28\x70\xaa\xaa\xfa\x55\x55\xe5\x55\x55\xe5\xe1\xdf\ -\x8d\x8e\xf3\xdc\x01\x00\x28\x00\x90\xf1\x7b\x22\x91\x20\xe9\x74\ -\xda\x4d\xa5\x52\x6e\x2a\x95\x92\x7a\x7b\x7b\x7d\xa9\x54\xca\xf5\ -\xac\x91\x48\x24\x42\x01\x3c\x87\x52\x4d\xd3\x90\x61\x18\xa8\x5a\ -\xad\xe2\x7a\xbd\x8e\x6d\xdb\x46\xae\xeb\x22\x84\x10\x08\x82\xc0\ -\x82\xc1\x20\x8d\xc7\xe3\x04\x63\x4c\x00\xc0\x05\x80\x06\x00\x58\ -\x63\x97\x33\xb6\x46\xc2\xe1\x30\x51\x14\x85\x0a\x82\xc0\x10\x42\ -\x40\x29\x05\xdb\xb6\x91\x69\x9a\xb8\x5a\xad\x82\x61\x18\xa0\xeb\ -\xfa\xa4\x7d\x62\xd2\x08\xfa\xfb\xfb\x61\x78\x78\x18\x97\xcb\x65\ -\xa4\x69\x1a\xd6\x75\x1d\x57\x2a\x15\xce\x30\x0c\x5c\xaf\xd7\xf1\ -\xe8\xe8\x28\x67\x59\x16\xd7\x68\x34\x38\x4a\x29\x30\xc6\x00\x63\ -\x4c\x7d\x3e\x1f\xf5\xfb\xfd\x44\x92\x24\x2a\xcb\x32\x09\x85\x42\ -\x34\x1c\x0e\xd3\x48\x24\x42\xa3\xd1\x28\x8d\xc5\x62\x74\xdd\xba\ -\x75\x93\x7e\xdf\xe3\x23\x90\xbd\x1b\xc5\x1c\x8c\x8c\x5d\x33\x19\ -\xe7\x19\xcf\x4c\x26\xff\x03\x5f\x76\x6c\xdf\xcf\xf6\x76\x77\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x05\xdc\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x05\x59\x49\x44\ -\x41\x54\x58\x85\xc5\x96\x7d\x88\x14\x65\x1c\xc7\x7f\xcf\x33\xb3\ -\xb3\x33\x3b\xbb\xb3\xef\xde\xe9\xbe\x1c\xa6\x69\x92\x52\x84\x89\ -\x60\xa9\x89\x65\x05\x52\x84\x82\x68\x6f\x9a\x78\x7f\x6c\xfd\x51\ -\x41\x7f\x04\x45\x04\x41\x14\xd2\x5f\x9b\x70\xa4\x24\x04\xda\x0b\ -\x8a\x51\x94\x85\x51\x60\xfd\xe3\x65\x45\xa7\x5e\x7a\x68\x77\xb7\ -\x73\xb7\xeb\xdd\xde\xcc\xce\xee\xde\xbc\xec\x3c\xcf\xd3\x1f\xdd\ -\x9d\x73\xdd\xde\x8b\xde\x49\x3f\x18\x66\x78\x7e\x2f\xdf\xcf\xfc\ -\x7e\xc3\x33\x0f\x02\x80\xc5\x00\x50\x87\xff\xc7\x64\x1e\x00\xea\ -\x8c\x31\x23\x97\xcb\x05\x09\x21\xf7\x21\x84\xf0\xed\x54\x64\x8c\ -\x51\x8e\xe3\xce\xe7\xf3\xf9\x1a\x42\x08\xf8\x71\x47\x80\xd2\xaf\ -\xdb\x77\xef\x8e\x0b\x92\xc4\xcf\x54\x60\xbe\x66\x56\xab\x76\xc7\ -\xf1\xe3\x43\x00\xb0\x15\x00\x6e\x00\xac\x59\xb9\x52\x59\x4e\x69\ -\x0f\x1c\x3c\x78\xf6\x76\x08\x7f\x3b\x38\x98\x7c\xe7\xe2\xc5\x8d\ -\x1d\xf9\x7c\x63\x79\x36\xab\x8c\xaf\x4f\x00\x20\x84\x00\x0c\xa3\ -\x06\x5d\x5d\xc6\x42\x89\x6a\x84\xf0\x7b\x55\x75\xeb\x99\x7a\x7d\ -\x73\x83\x31\xff\x26\x59\xfe\x71\x55\x22\x61\xff\xd4\xd3\x93\x9e\ -\x02\xb0\x90\x56\x26\xc4\xf7\xe0\xb5\x6b\xfb\xae\x39\xce\x0a\x8b\ -\xb1\x20\x00\x40\x92\xe7\x0b\xa7\xdb\xda\x4e\x01\xc0\xa3\xde\xd8\ -\xdb\xf2\xc1\x29\x18\xbb\x2d\x3c\x3f\x6c\x33\x26\x03\x00\x0b\x62\ -\xac\xff\xbc\x74\xe9\xc1\x66\xb1\x0b\xde\x81\x0b\xb6\x2d\x3f\xd9\ -\xd7\xb7\xaf\xc7\x71\x56\x87\x39\x6e\xc8\x61\x4c\x7c\x6b\xd1\xa2\ -\xc3\x77\x0a\xc2\x68\xb3\xf8\x05\xed\xc0\xa1\x91\x91\x3b\xd6\x5f\ -\xbd\xfa\x46\x8f\xe3\xac\x5e\xe5\xf7\x9f\x3f\xd3\xd6\xf6\xde\xc3\ -\xb2\x7c\xe6\xd5\x78\xfc\xf2\x74\x39\x0b\xd6\x81\x9d\xfd\xfd\x5b\ -\x4f\x18\xc6\x53\x00\xc0\x76\x85\xc3\x9f\x1e\x4b\xa7\x7f\x18\xa5\ -\x14\x9f\xca\x66\xbf\x99\x29\x6f\xde\x00\x57\x1c\x27\xb0\xbd\xaf\ -\xef\xb9\xbf\x6c\xfb\x5e\x05\xe3\xf2\xfb\xad\xad\x1d\x07\xa2\xd1\ -\xbf\x01\x00\x02\x18\xd3\xd9\xf2\xe7\x05\x70\x44\xd3\xda\x5e\x2e\ -\x16\x0f\x18\x94\x26\x56\x08\xc2\x1f\x5f\x66\xb3\x1f\xaf\xf4\xfb\ -\x9b\xce\x7a\xc1\x01\x9e\x2e\x14\x36\x1f\xab\x54\x76\x02\x00\xde\ -\xa1\x28\x5f\x7c\x9e\xc9\x7c\x7f\x2b\x75\x6e\x1a\xa0\xaf\xd1\x10\ -\x1f\xef\xed\x7d\xe6\x82\x6d\xaf\x0d\x62\xac\xbd\xdb\xd2\xd2\x91\ -\x8b\xc5\xae\xde\x8a\xf8\x4d\x03\x7c\xa2\xeb\xe9\x97\x8a\xc5\x76\ -\x9d\x90\x45\xcb\x04\xa1\xeb\x54\x36\x7b\xe4\x6e\xbf\x7f\x5e\x7f\ -\xd2\x59\x01\x6a\x94\x72\x41\x8c\xc9\x0b\xaa\xfa\xc0\xd1\x4a\x65\ -\x17\x65\x8c\x7b\x22\x14\x3a\x79\x22\x9b\x3d\x8d\x01\xd8\x7c\xc4\ -\x67\x05\xd8\x53\x28\x3c\xf4\x7c\x24\xf2\xe7\x6b\xa5\xd2\xf6\xdf\ -\x2d\x6b\xbd\x8c\xb1\xfe\x76\x4b\xcb\x47\xaf\xc4\xe3\x57\xe6\x2b\ -\x3c\x2b\xc0\x51\x5d\xcf\x9c\x30\x8c\xed\xa7\x6b\xb5\x4d\x65\x42\ -\x16\x2f\x15\x84\x4b\x27\x33\x99\xc3\xf7\x88\x62\x75\xa1\xc4\x27\ -\x01\x58\xb6\x8d\x2f\xab\xaa\xa4\x9b\x66\xb8\x42\x88\xef\xc5\xc1\ -\xc1\x9c\xcd\x58\xc0\x26\x24\xb0\x56\x92\xce\x7e\xd0\xda\xfa\x95\ -\xcb\x18\xfa\xcd\xb2\x42\x00\x37\xb6\x50\xef\x18\x30\x42\x6c\x06\ -\x1f\x00\x00\x44\x74\xdd\x47\x29\x45\x53\x00\x6c\xdb\xc6\x3d\xf5\ -\x7a\x60\xc0\xb2\x22\xaf\x5f\xbf\xfe\x6c\x8d\xd2\x28\x00\x80\x80\ -\x90\x59\x74\xdd\x96\x73\xa6\x99\x88\x71\x9c\x05\x00\x30\x91\xed\ -\x11\x41\x63\x02\x93\x44\xff\xe3\x03\x00\xc8\x0c\x0c\x88\x0d\xd7\ -\x9d\x0a\x60\x39\x0e\xee\x1d\x1e\x96\x0e\x6b\xda\x26\x9d\x90\xa4\ -\x88\x50\x6d\xb9\x20\x74\x6f\x0b\x85\x7e\x15\x11\x72\xcb\x84\x48\ -\x23\x84\x48\x63\x00\xcc\x7b\xf7\x42\x8d\x77\xc1\x0b\xe9\x8d\x77\ -\x07\x07\x25\xd7\x43\xe4\xed\x00\x1a\x18\x19\x69\x19\xe1\x79\xf1\ -\xb1\x4c\xe6\x97\xc5\x81\x80\x81\x00\xa0\x0e\xd0\x3a\x3a\x56\xd4\ -\x5b\x18\x35\x5b\xbb\xf1\xc6\xd3\xc6\x4b\xa6\x19\x69\xf8\x7c\xce\ -\x14\x00\xb5\x54\x2a\xd9\x00\x77\x6d\xdc\xb6\x8d\x07\x80\x35\x96\ -\xa7\x75\xe3\xc9\x08\x21\x60\x00\x80\x18\x43\x13\x2f\xe1\xf1\x4d\ -\x88\x8e\xe7\x35\x19\x41\xbf\xae\xdb\x0c\xe3\x4b\x53\x00\x88\x28\ -\x3e\x62\x13\x72\x7f\xb1\x58\x8c\xc1\x34\x86\x10\x62\xc9\x64\x72\ -\x8f\x24\x49\x1b\x01\x21\xe2\xf5\x31\x00\xb0\x2c\xab\xab\x54\x2a\ -\x7d\x38\x53\x7e\x3a\x9d\x2e\xfb\x38\xee\xbc\xb7\x43\x0a\x63\x6c\ -\x4e\xe7\xc0\xfd\xfb\xf7\xc7\x42\xa1\xd0\xd9\x64\x32\x19\x6c\xe6\ -\x1f\x1a\x1a\xd2\x1c\xc7\xd9\x90\xcf\xe7\x6b\x73\xa9\x87\x10\x52\ -\xe6\x7c\x20\xc9\xe5\x72\x3b\x02\x81\xc0\x77\xb1\x58\x2c\x3c\x5d\ -\x4c\x24\x12\x49\x00\xc0\x67\xed\xed\xed\xcb\xe6\x5a\x77\xc6\x0e\ -\xec\xdd\xbb\x37\x22\x8a\xe2\x21\x00\xd8\x80\x10\x0a\x8b\xa2\x38\ -\x30\x5b\x41\x42\x88\xdf\xb2\xac\x2c\x42\x48\x03\x80\x4e\x4a\xe9\ -\x9b\x1d\x1d\x1d\xe7\x9a\x8a\x23\xa4\x4c\x0b\x50\x2a\x95\xb8\xce\ -\xce\x4e\xbe\xbb\xbb\x5b\x11\x45\xd1\x45\x08\x11\x4d\xd3\xb8\x4a\ -\xa5\x82\x6b\xb5\x1a\x36\x4d\x13\xb9\xae\x0b\x00\x80\x38\x8e\x63\ -\xa2\x28\x32\x59\x96\xa9\xa2\x28\x34\x1a\x8d\x52\x49\x92\x50\xb9\ -\x5c\xf6\x2d\x59\xb2\xc4\xdc\xb2\x65\x8b\x99\x4e\xa7\x49\x33\x80\ -\x89\x8f\xd0\x34\x4d\x54\x28\x14\x78\x55\x55\x39\x55\x55\xf9\xb1\ -\x67\xbe\x50\x28\x70\xaa\xaa\xfa\x55\x55\xe5\x55\x55\xe5\xe1\xdf\ -\x8d\x8e\xf3\xdc\x01\x00\x28\x00\x90\xf1\x7b\x22\x91\x20\xe9\x74\ -\xda\x4d\xa5\x52\x6e\x2a\x95\x92\x7a\x7b\x7b\x7d\xa9\x54\xca\xf5\ -\xac\x91\x48\x24\x42\x01\x3c\x87\x52\x4d\xd3\x90\x61\x18\xa8\x5a\ -\xad\xe2\x7a\xbd\x8e\x6d\xdb\x46\xae\xeb\x22\x84\x10\x08\x82\xc0\ -\x82\xc1\x20\x8d\xc7\xe3\x04\x63\x4c\x00\xc0\x05\x80\x06\x00\x58\ -\x63\x97\x33\xb6\x46\xc2\xe1\x30\x51\x14\x85\x0a\x82\xc0\x10\x42\ -\x40\x29\x05\xdb\xb6\x91\x69\x9a\xb8\x5a\xad\x82\x61\x18\xa0\xeb\ -\xfa\xa4\x7d\x62\xd2\x08\xfa\xfb\xfb\x61\x78\x78\x18\x97\xcb\x65\ -\xa4\x69\x1a\xd6\x75\x1d\x57\x2a\x15\xce\x30\x0c\x5c\xaf\xd7\xf1\ -\xe8\xe8\x28\x67\x59\x16\xd7\x68\x34\x38\x4a\x29\x30\xc6\x00\x63\ -\x4c\x7d\x3e\x1f\xf5\xfb\xfd\x44\x92\x24\x2a\xcb\x32\x09\x85\x42\ -\x34\x1c\x0e\xd3\x48\x24\x42\xa3\xd1\x28\x8d\xc5\x62\x74\xdd\xba\ -\x75\x93\x7e\xdf\xe3\x23\x90\xbd\x1b\xc5\x1c\x8c\x8c\x5d\x33\x19\ -\xe7\x19\xcf\x4c\x26\xff\x03\x5f\x76\x6c\xdf\xcf\xf6\x76\x77\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x88\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x03\x05\x49\x44\ -\x41\x54\x58\x85\xc5\x97\xcb\x6b\x14\x41\x10\xc6\x7f\xb5\xbb\x9a\ -\x68\x74\x34\x04\x11\xf1\x99\x68\x04\x0f\x1a\xc4\xb8\x33\x89\xaf\ -\x83\x08\x8a\x06\xf1\xa0\x87\x78\x51\x44\xc5\x08\xb9\x28\x78\x57\ -\x14\xd4\x83\xde\x44\x14\xbd\xf8\x0f\x48\xc0\x83\x37\xf1\xb0\x0f\ -\xf1\xa6\xf8\x00\x25\x44\x22\x0a\x1a\x34\xb8\x1a\xd7\xec\x94\x87\ -\xee\x89\x93\x71\x36\x0f\x98\x6c\x0a\x8a\xde\xe9\xaa\xad\xfa\xba\ -\xea\xeb\x9e\x1e\x01\x96\x01\x25\x66\x47\x1a\x32\x40\x49\x55\x87\ -\x67\x23\xbb\x88\x90\x9a\x8d\xc4\x61\xa9\x0a\x40\x44\x8e\x8b\x48\ -\x63\x74\xbe\xe0\x79\x2b\xf2\x1d\x1d\xdb\xc2\x73\xcf\xb2\xd9\xdd\ -\x45\xd7\x6d\xaa\x12\x67\xa1\x88\x9c\x10\x91\xd8\x5c\xb1\x93\x22\ -\xb2\x0b\xb8\x07\xac\x8e\x31\x0f\x8b\xea\xfd\xa2\xeb\xee\xb7\x80\ -\x7a\x54\xe4\xe2\xcf\xf9\xf3\xbf\x57\x59\x4b\x13\x70\x17\xe8\x8a\ -\xcd\x05\x38\x51\x0e\x88\xc8\x63\x60\x0f\xd0\xa8\xaa\xdf\xa2\x7f\ -\xca\x75\x76\x6e\x4e\xf9\x7e\x9f\x8a\x9c\x14\xd5\x3b\x29\xdf\xef\ -\xd8\x5a\x2c\x7e\xa8\xb2\x98\x0c\xf0\x1b\x78\xae\xaa\xd9\x88\xcd\ -\xc1\x02\x20\x50\xa0\x15\xf0\x81\x1f\xe1\xf9\xa8\xe6\x3c\xaf\x37\ -\xef\xba\x9a\x77\xdd\x83\x13\xf9\xd9\x98\x9f\x01\x05\xb6\x44\xe6\ -\x9d\xb8\x16\x9c\xb7\xe3\x60\xdc\x8a\x42\xe2\x02\x1f\xed\x38\x99\ -\x0c\xd8\xf1\x42\xd4\x30\x0e\x80\x25\xdd\x31\x4c\x6b\xde\x55\x8b\ -\x56\xf0\xbc\x53\xa2\xba\x56\x54\x37\x89\xea\x91\x5c\x67\xe7\xde\ -\x49\x00\xbc\xb1\xe3\x21\x11\x59\x5e\x15\x00\x70\x1a\xa8\x00\xa3\ -\xc0\xeb\xb8\x48\x45\xd7\x6d\x03\x2e\xa5\x7d\xbf\x3b\x5b\x28\x7c\ -\xf5\x53\xa9\xa3\x29\xdf\xbf\x57\xf0\xbc\x15\x13\x00\x78\x0b\xfc\ -\xb1\xda\x1b\x0b\x40\x44\xe6\x60\xca\x3f\x0f\x43\x9a\xfe\xb8\x48\ -\x29\xdf\x1f\x49\x57\x2a\x3b\xdb\x8b\xc5\xf7\x00\x5e\x2e\x57\x10\ -\xd5\x7d\x6a\xc8\x56\x4d\xfa\x6d\xf2\x79\xc0\x59\x11\x69\x08\x1b\ -\x1d\x4b\x88\x6e\xe0\x27\x86\x2c\x25\xa0\x6b\x32\x72\x4d\x55\x81\ -\x1d\x40\x39\x14\xbb\x27\x20\x61\x18\xc0\x4b\xeb\xa0\x98\x36\x6c\ -\x4c\x10\xc0\xca\x50\x6c\xc5\x90\x52\x00\x27\x63\xcb\xbf\x03\xb3\ -\xfd\xc2\xad\x39\x23\x22\xe5\x09\xca\x3a\x1d\x11\x9b\x58\xec\xf3\ -\x12\xe0\x00\xf0\x24\x28\xc3\x23\x4c\x8f\xb4\x46\x5a\x01\x72\x36\ -\x37\x6d\x18\xd6\xd7\x2a\x79\xa0\xa3\xc0\xf6\x34\x70\x0e\x68\x07\ -\x26\x62\xf1\x4c\x48\x05\xd0\x14\xa6\x0f\xb5\x4e\x0e\xe6\xb8\x1f\ -\xe3\xc0\x6b\x6a\xdf\x82\x41\x60\x71\xb0\xf2\x2b\xc0\x6d\xa0\x3e\ -\x84\x70\xc0\x3a\x26\x25\xab\xf8\xb7\x0b\x7e\x01\x57\x31\x55\xc0\ -\x01\xe6\x02\x43\x11\x84\xad\x09\x9e\x03\x4b\x22\xb1\x4b\xc0\x02\ -\x82\xb7\xa1\xaa\x96\x81\x1b\xc0\x88\x45\x38\x02\xac\x49\x70\xf5\ -\x6b\x30\xa4\x0b\x62\xdf\x56\xd5\x1f\x30\xfe\x65\x74\x0b\x48\xdb\ -\xdf\x95\x19\x00\x10\x1c\x6a\x73\x80\x9b\x81\x61\x0c\x80\xaa\x7e\ -\x01\x1e\x58\xc7\x0c\xd0\x9c\x20\x80\x66\x4c\xff\x47\x81\x3e\x55\ -\x0d\xee\x07\xff\xbd\x8e\xaf\x63\xaa\x50\x07\xac\x4b\x10\x40\x0b\ -\x86\xe0\x8a\x21\xdf\x98\x8c\x03\xa0\xaa\xaf\x80\xa7\xf6\x71\x7d\ -\x82\x00\x36\xd8\xf1\x85\xaa\xe6\xa3\xc6\xe8\x9d\x70\x8f\x45\x3a\ -\x94\xe0\x2e\x08\xb6\xf4\xe1\xe8\x9d\xf0\x3f\x00\xd6\xf0\x0e\xb3\ -\x47\xeb\x13\x02\x50\x06\x3e\x01\xe9\xa9\x5c\x4a\x01\x2e\x63\x48\ -\x13\xf7\x5d\x30\x2d\x11\x91\xa5\x18\xe6\x5f\x53\xd5\x4a\x9c\x4f\ -\x5c\x05\xea\x80\x87\x40\x4b\x02\xab\x5f\x06\xf4\x01\x8b\x62\x6c\ -\x4e\xec\x87\x49\xad\x44\x44\x9c\x0c\xd0\x20\x22\x93\x3a\xcf\x90\ -\x34\xfc\x05\xec\x55\xee\xee\x8b\xa5\x1a\x87\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\xc2\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x10\x00\x00\x00\x10\x08\x06\x00\x00\x00\x1f\xf3\xff\x61\ -\x00\x00\x03\x89\x49\x44\x41\x54\x78\x9c\x62\x64\x40\x03\xa2\xa2\ -\xa2\x16\xc9\xc9\xc9\x89\x6c\x6c\x6c\xcc\x0c\x0c\x0c\x0c\xff\xff\ -\xff\x67\x60\x62\x62\x62\x7c\xf3\xe6\x0d\xf3\xd2\xa5\x4b\x57\x7c\ -\xf8\xf0\x61\x07\xb2\x7a\x00\x00\x00\x00\xff\xff\xc2\x40\xb6\xb6\ -\xb6\xc5\xff\xb1\x80\x2f\x5f\xbe\xfc\xdf\xb6\x6d\xdb\x4b\x39\x39\ -\x39\x1f\x64\xf5\x00\x00\x00\x00\xff\xff\x62\x42\x37\xe0\xff\xff\ -\xff\xcc\x0c\x0c\x0c\x0c\x7f\xff\xfe\x65\xf8\xfb\xf7\x2f\xc3\xef\ -\xdf\xbf\x19\x7e\xfd\xfa\xc5\xf0\xf6\xed\x1b\x06\x15\x15\x55\xb1\ -\x5d\xbb\x76\xcd\x47\x36\x04\x00\x00\x00\xff\xff\x64\xcc\x31\x01\ -\x80\x30\x0c\x00\xb0\x80\x06\xce\x9e\xf3\x83\x44\x1c\x0c\x29\xdd\ -\xf8\x87\x95\x22\x80\x08\xc8\x2f\x40\x41\xe6\x90\x39\xcc\xf9\xa8\ -\x2a\x6c\xde\xb5\x44\xc4\xd1\xef\x7e\xb5\xd6\x4e\xec\x1f\x00\x00\ -\x00\xff\xff\x00\x41\x00\xbe\xff\x01\x32\x32\x31\x11\x18\x18\x18\ -\x6f\x0b\x0d\x0e\x17\xff\xfe\xfe\xfe\xf2\xf1\xf2\x31\xb9\xb9\xb8\ -\x39\xf7\xf7\xf7\x00\x00\x01\x00\x00\xff\xfe\xff\x00\x00\x00\x00\ -\x00\xf5\xf6\xf6\x00\xc9\xc8\xc7\x00\xce\xce\xcf\x00\x18\x19\x18\ -\x00\xfe\xfd\xfe\xf5\x7b\x7b\x7b\x5b\x00\x00\x00\xff\xff\x62\x71\ -\xf7\xf4\x9c\xdd\x5a\x57\x19\x0c\xb3\x7e\xf9\xca\x35\x0c\x0c\x0c\ -\x0c\x0c\x57\xaf\x5e\xc3\x70\x9a\x9c\x9c\x1c\xc3\xc7\x8f\x9f\x18\ -\x3e\x7f\xfe\xc4\xa0\xa0\xa0\xc8\x2d\x2b\x2b\x6b\x00\x00\x00\x00\ -\xff\xff\x24\xc5\xb1\x11\x80\x20\x0c\x40\xd1\xcf\x9d\x0d\x16\x0c\ -\x90\x56\xfa\xac\xe4\x40\x0e\xc5\x24\xdc\x31\x44\x80\xc6\xc4\xc2\ -\xd7\xbc\x63\xce\x05\x40\x6a\xcf\x7f\x1f\xc0\x4d\xad\x17\x09\x08\ -\x82\xf0\xe0\x75\x67\xef\x85\xaa\x62\x66\x88\x08\xe5\xcc\xf9\x03\ -\x00\x00\xff\xff\x62\xf9\xf7\x1f\xe2\xc4\x3f\x2e\x95\x0c\x0c\x0c\ -\x0c\x0c\x7f\x5f\xaf\x62\x60\x60\x60\x60\xb8\x73\xe7\x2e\x24\x5a\ -\x45\x04\x18\xae\x9f\x39\xc1\xf0\xee\xe5\x73\x14\xd7\xf0\x6b\xc8\ -\xfc\x54\xe7\xf9\xa5\x04\x00\x00\x00\xff\xff\x62\x81\xea\x67\x78\ -\x78\xe1\x38\xc3\xde\xed\x3b\x19\x3e\x7f\xfb\xce\xb0\x69\xe1\x57\ -\x86\xdf\xbf\x7f\x33\x30\x30\x30\x30\x7c\x16\x97\x60\xb0\x37\xd6\ -\x60\x60\x60\xd0\x40\x31\x80\xf3\xf4\x8c\xdf\xdf\x7e\xfd\xfb\x06\ -\x00\x00\x00\xff\xff\x62\xf9\xff\xff\x1f\xc4\xe6\xe7\x37\x18\x62\ -\xa3\x42\x30\xfc\xcd\xfa\xe4\x30\xc3\xbf\x27\x4f\x19\x18\xfe\xfc\ -\x64\xf8\xff\xfb\x3b\xc3\xbf\x5f\xdf\x18\xd8\xbe\xbe\xfa\xf2\x49\ -\x40\xeb\xdf\xcb\x1f\xe7\x9e\x02\x00\x00\x00\xff\xff\x04\xc1\x41\ -\x0a\x80\x20\x10\x40\xd1\x6f\x4a\x41\x1d\xa1\x13\xb4\xeb\xfe\x57\ -\x68\xdb\x3e\xf1\x00\x41\x58\x90\x93\xce\xf4\x5e\x30\x1c\x29\x45\ -\xfa\xeb\x20\x6c\x3b\xe9\xf1\xcc\xcb\x4a\x79\x6f\x68\x1f\xa2\x05\ -\x6b\x82\x35\xc1\x69\xc5\x54\xa9\x7e\x0a\x99\xf1\x94\x6e\xc8\x3f\ -\x00\x00\x00\xff\xff\x2c\xd0\x51\x0a\x80\x20\x10\x45\xd1\x3b\xcf\ -\xc1\x4d\xb8\xff\x75\x05\x41\xff\x9a\x10\x52\x63\xf6\xd3\x59\xc2\ -\xf1\x85\x68\xc7\x46\xe9\x3b\x11\x0d\xaf\x95\x99\x4f\xee\xab\x83\ -\x19\xc8\x40\xe2\x1f\x85\x05\xf1\x0c\x4f\xb9\xa4\x57\x9a\x1f\x00\ -\x00\x00\xff\xff\x62\xf9\xf7\xf7\x0f\xcb\x9f\x47\x67\x19\xf8\x5e\ -\x5f\x60\xf8\xc7\xf0\x9f\x81\xe7\x1f\x33\x03\xcb\xa7\x67\x0c\x3c\ -\x7f\x7e\x42\x34\x33\x30\x42\x0c\x62\xe3\x60\x60\x60\xf8\xcf\xc0\ -\xf8\x9f\x81\xe1\x17\x23\x1b\xc3\x2f\xb3\x84\xaf\xff\xff\x6f\x65\ -\x06\x00\x00\x00\xff\xff\x62\x79\x71\xf3\xc2\xc7\x07\x2c\xcc\x1f\ -\x64\x39\x7e\x0a\xfc\x65\x65\x67\xf8\xf1\x8f\x81\xe1\xdd\xab\x77\ -\x0c\x8c\xcc\x2c\x50\xdb\x99\x19\x18\x98\x18\x18\x18\x18\x7e\x33\ -\x30\xfc\xff\xcf\xc0\xcc\xc8\xc0\x70\xeb\xf5\x9f\x1f\xcb\xca\x2b\ -\x5e\x5c\xbd\x7a\xf5\x01\x00\x00\x00\xff\xff\x62\xe4\x62\x61\xb4\ -\xe6\x67\x67\x92\x65\x67\x61\x92\xfe\xf7\x9f\xe1\xef\xdf\xff\x0c\ -\x6c\x7f\xff\x33\x70\xfe\x87\x38\x1a\x01\xa0\x5e\x60\x64\x64\x60\ -\xfa\xf5\xe7\xff\xa7\x77\xdf\xff\x9c\x62\x60\x60\xb8\x02\x00\x00\ -\x00\xff\xff\x62\x60\x60\x60\x60\xc1\x08\x7a\xc2\x80\x89\x81\x81\ -\x81\x8d\x81\x81\x81\x11\x00\x00\x00\xff\xff\x03\x00\xed\x15\x52\ -\x60\x15\x7d\xfb\x19\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x05\x1c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x04\x99\x49\x44\ -\x41\x54\x58\x85\xbd\x57\x3d\x6f\x13\x59\x14\x3d\xf7\xcd\x78\xec\ -\xf5\x38\xb1\x63\xc2\x8e\xbc\x1b\xc0\xb0\x2c\x34\x0b\x4b\x44\xc3\ -\x92\x1f\x00\x15\xa4\xa6\x45\x42\x48\xfc\x05\x1a\x2a\x1a\x52\x21\ -\x21\x9a\x28\x4a\x43\xc1\x56\xac\x44\x81\xf8\x09\x54\x91\x00\x29\ -\x7c\x44\x41\x68\x09\xb6\x13\x7b\x27\x09\x19\xcf\xbc\x8f\xbb\x85\ -\xc7\x66\xc6\x4e\xd8\xd1\x4a\xe6\x4a\x23\xf9\xd9\x6f\xee\x39\xef\ -\xdc\xf3\xee\x7b\x26\x00\x35\x00\x5f\x6e\xdf\xbe\xfd\xcb\x89\x13\ -\x27\x66\xf0\x1d\xe2\xd5\xab\x57\x1f\x16\x16\x16\xd6\x01\xb8\x00\ -\x30\x79\xff\xfe\xfd\xbf\xa2\x28\xd2\x4a\x29\x33\xee\x47\x6b\x6d\ -\xc2\x30\xd4\x77\xef\xde\x7d\x02\x60\x52\x9c\x3d\x7b\xd6\x3d\x79\ -\xf2\xe4\x5c\x2e\x97\x83\x94\x72\xec\xab\x97\x52\x1a\xc7\x71\x50\ -\xaf\xd7\xff\x38\x77\xee\x5c\xc9\xce\xe7\xf3\x76\xb1\x58\x34\xc6\ -\x98\x50\x6b\x9d\x2b\x14\x0a\x62\x9c\x04\x82\x20\x90\x8e\xe3\x50\ -\xb1\x58\x54\xb9\x5c\xce\xb2\x01\xc0\x18\xc3\xcc\xac\xa4\x94\x16\ -\x00\x1a\x27\x01\xa5\x94\x62\x66\xc1\xcc\x00\x00\x1b\x00\xe2\x81\ -\xee\xfd\xc6\xe3\xc4\x87\x94\x52\x33\x33\x1b\x63\x78\x40\xc0\x18\ -\x03\x66\x56\x4a\x29\x03\x60\xac\x0c\xa4\x94\x1a\x00\x1b\x63\x90\ -\x24\xc0\xcc\x6c\xa4\x94\xfc\x3d\x08\x30\x33\x46\x4a\xc0\xcc\x3a\ -\x56\x60\xac\x11\x2b\x80\xe1\x12\x30\x00\xf5\x3d\x14\x88\xa2\x68\ -\x54\x81\xd8\x03\x5a\x4a\x99\xf2\x40\xbb\xdd\x16\x3b\x3b\x3b\xff\ -\x1b\xac\x50\x28\xc0\xf3\xbc\x94\xaa\x71\x09\x68\x44\x81\x78\x1b\ -\xa6\x56\x5f\xad\x56\x4d\xb5\x5a\xcd\x8e\xd8\x68\xd8\xe4\x38\x16\ -\x88\x00\xad\xc1\x42\xa8\xe1\x29\x51\x14\x69\x00\x64\x8c\xa1\x01\ -\x81\x21\x0f\x0c\x48\xb4\x5a\x2d\xea\x74\x3a\x99\xfb\xc2\xaf\x95\ -\x8a\x45\xf9\xfc\x60\x4c\x80\xcd\x8d\x06\xe0\x79\x03\x22\x71\x09\ -\xc8\x18\x63\x0d\x08\x24\x15\x48\x36\x82\xe9\xe9\x69\x9e\x9e\x9e\ -\xce\x04\x4e\x1f\x3f\xe6\xc8\xb2\x80\x20\x00\x98\x01\x21\xfa\x88\ -\x16\x33\x0f\x7a\x7c\x9f\x00\x33\xa7\x08\xec\xeb\x81\x46\xa3\x21\ -\x5a\xad\x56\x26\x05\x8e\xfa\x3e\x55\x8e\x1d\x03\x00\xb4\xd7\xd6\ -\x74\xc5\xf3\x2c\x51\x2a\x81\x94\x22\x4e\xe4\x4c\x94\xe0\xab\x07\ -\xb8\x17\x7a\xd8\x03\x9e\xe7\x19\xcf\xf3\x32\x29\x80\x95\x15\x8b\ -\x77\x77\x01\x00\x95\x6a\x95\x29\x0c\x7b\xa8\xdd\x6e\x6a\x5a\xac\ -\x80\x18\x6e\x44\x88\x4b\x90\x52\x60\x63\x63\x83\x36\x36\x36\x32\ -\x1d\x4e\x3f\x35\x1a\xa8\xc5\xe5\xda\xdb\xde\x16\x6e\xb9\x0c\x44\ -\x11\xd0\xed\xa6\xb6\x76\x18\x86\x3a\x3e\x0b\x46\x76\x81\x1e\xee\ -\x03\xb5\x5a\x8d\x6b\xb5\x5a\xb6\xe6\xb4\xbe\x0e\xac\xad\xd9\x00\ -\xe0\x12\x09\xc4\xdb\x97\x85\xd0\x43\x04\xd4\x7f\x29\x90\xc8\xb9\ -\x2e\xb2\x2a\x00\x66\x5c\x68\x36\x21\x1c\x07\xa0\x9e\x6d\x58\x29\ -\xe0\xf2\xe5\x54\x0d\xc2\x30\xd4\x3d\xc8\x21\x0f\x18\x63\x74\x14\ -\x45\xa9\x12\xd4\xeb\x75\x5d\xaf\xd7\x75\x26\x02\x00\xb0\xba\x9a\ -\xc3\xde\x9e\xd5\x1f\xd2\xc4\x84\xe2\x89\x89\x94\xaf\xba\xdd\xae\ -\x66\x66\x7d\x90\x02\xa9\x6d\xd8\x6c\x36\x69\x73\x73\x33\xf3\x05\ -\x65\x46\x6b\x2e\x77\x3a\x00\x11\x0c\xc0\x1f\x67\x67\xa3\xa3\x43\ -\xe7\x7b\xec\x01\x3d\xdc\x8a\x99\x99\xfb\x0a\x0c\xc2\x75\x5d\x06\ -\x90\x49\x81\xfc\xfb\xf7\xf6\xe4\xfa\xba\x05\xdd\x9b\x4e\x42\x50\ -\xb9\x54\x1a\xf1\x4f\x42\x81\xd1\xfb\xc0\xb0\x09\x5d\xd7\x85\xeb\ -\xba\xe9\x0c\xcd\xa6\x85\x95\x15\x1b\x9b\x9b\x44\x9d\x8e\x60\xdf\ -\x27\xda\xdd\x15\xdc\x6e\x0b\x28\xf5\xf5\x65\x22\x94\x97\x96\x8a\ -\x54\xaf\x6b\x9e\x9a\x32\x7c\xfe\xbc\xa4\xe3\xc7\xf5\x41\x25\x60\ -\x63\xcc\x48\x23\x4a\x45\x10\x10\x96\x97\x0b\x78\xfe\xdc\x41\x14\ -\x11\x00\x70\xdf\x6c\x94\xe8\x55\xfd\xcf\x44\x40\xab\x25\xf8\xf5\ -\x6b\x01\x22\xd0\xe3\xc7\x79\x9a\x9b\x8b\xf2\xdb\xdb\x76\xcf\x72\ -\x09\x05\xe2\x18\xdc\x52\xf6\x8d\x5b\xb7\x4a\x78\xf3\x66\x60\xb0\ -\x14\x50\xff\xab\x72\xd9\xb0\x6d\x33\x7c\x5f\x20\x3e\x6c\x92\xf3\ -\xf8\xc9\x13\x67\xee\xd0\xa1\x9f\x01\xfc\xdd\x7f\x27\x49\xe0\xe0\ -\xf8\xf0\x41\xe0\xc5\x0b\x6b\x90\xf0\xc8\x11\x8d\xad\x2d\x81\x20\ -\xf8\x8a\x3e\x33\xa3\x79\x79\x79\x17\xd5\x2a\x83\x19\x7c\xed\x5a\ -\x89\x56\x57\xed\x61\x92\x3f\x38\x4e\x2e\x99\x3a\x9b\xc3\x3d\x8f\ -\x39\x08\x98\x7d\x1f\xec\xfb\xe0\x97\x2f\x2d\xfe\xfc\x99\x06\xe3\ -\xd9\x59\x89\x47\x8f\x7a\xe0\x31\x20\x2d\x2d\x7d\xc1\x85\x0b\x11\ -\xb6\xb7\x01\xdf\xef\x3d\xae\x6b\x9e\x9e\x3a\xf5\x3e\x99\x3a\x9b\ -\x02\x85\x02\xd3\xd5\xab\x11\x2f\x2e\xe6\x53\x2b\x2a\x14\x18\x77\ -\xee\x04\x74\xe3\x46\xb4\xdf\x3b\x78\xf0\x60\x8f\x17\x17\x15\x5a\ -\x2d\x41\xa7\x4f\x6b\x5c\xbc\xa8\x76\x17\x16\x14\x80\x41\x29\xb3\ -\x11\x00\x80\x7b\xf7\x02\xd4\x6a\x06\x4f\x9f\xe6\x50\xa9\x30\xcd\ -\xcf\x4b\x5c\xb9\x22\x31\x35\xf5\xcd\x2b\x1c\x5d\xbf\x3e\x4a\x2e\ -\x11\xb6\x94\x52\xb7\xdb\x6d\x2e\x97\xcb\xbf\x07\x41\x50\x7a\xf7\ -\xee\x5d\xfe\xc0\xd9\xf3\xf3\xc0\xfc\x7c\xff\x6c\x27\x6c\x6d\x39\ -\xd8\xda\xca\xbc\x06\x00\x38\x7c\xf8\xf0\x4c\xb1\x58\x2c\xfb\xbe\ -\xdf\xd5\x5a\x1b\x02\x30\x79\xf3\xe6\xcd\x3f\xcf\x9c\x39\xf3\xa3\ -\x6d\xdb\x53\x4a\xa9\xb1\xfe\x33\xaa\x56\xab\xf2\xd3\xa7\x4f\xff\ -\xbc\x7d\xfb\x76\xe7\xe1\xc3\x87\x57\x09\x40\x2d\x9f\xcf\xef\x5d\ -\xba\x74\xe9\x37\xcb\xb2\x0a\xe3\x04\xef\x87\xd6\xba\xfb\xec\xd9\ -\xb3\x97\x61\x18\x16\xff\x05\xd5\xbd\xad\x4b\xfb\xbb\x2b\x61\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x8b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\ -\x06\x62\x4b\x47\x44\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\ -\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\x01\ -\x42\x28\x9b\x78\x00\x00\x00\x07\x74\x49\x4d\x45\x07\xdb\x03\x10\ -\x0f\x0d\x22\xc8\x06\x13\x97\x00\x00\x02\x0b\x49\x44\x41\x54\x58\ -\xc3\xed\xd7\xcf\x8b\x4e\x61\x14\x07\xf0\xcf\x9d\x5f\xd4\xd4\x2c\ -\xfc\x28\xbf\x53\x0a\x3b\x91\x8d\x8d\x51\x42\x11\x0b\x9a\x48\x64\ -\x61\x61\x81\x22\x59\xb1\x23\x1b\x45\x42\xca\x42\x29\x4d\xcc\x44\ -\xf9\x03\x14\x2b\xa3\x64\x89\x42\x46\xf9\x11\x0b\x66\x26\xc2\x88\ -\x63\xe1\x8c\x6e\xef\xbc\xef\x98\x85\x79\xdf\xcd\x3c\xf5\xdc\x73\ -\x9f\xf3\x7d\xce\x73\xbe\xf7\xdc\xd3\x39\xf7\x16\x98\x8d\x2f\x1a\ -\x33\xda\x5b\xd2\xf9\x50\x83\x08\x68\xa9\x93\x9f\xdd\xd8\x5f\xa1\ -\x7b\x87\x3d\x4d\x75\x22\xb0\x06\x2b\xd0\x56\x0d\xec\xa8\x03\x81\ -\x43\x08\x2c\xac\xf4\xdd\xa4\xc1\x63\x92\xc0\x24\x81\x49\x02\x93\ -\x04\xea\x45\x60\xcc\x9e\x33\x52\x8a\xaf\x67\xb9\x9c\xc8\x39\xaa\ -\x14\x97\x99\xdd\x46\xff\x04\x45\x60\x25\xd6\xfe\x2b\x02\x8d\x6f\ -\x46\xc1\x82\xe0\x7a\xf0\x20\x38\x19\xb4\x56\x3b\x2d\x58\x19\x9c\ -\x0f\xee\x06\x47\x82\x19\x25\xec\x60\xea\x2f\x07\xcb\xc7\xc3\xae\ -\xa3\x64\xfc\x28\xf8\x10\x5c\x0b\x22\x38\x5e\xc5\x79\x5b\xf0\x3a\ -\x78\x16\x5c\x0d\xbe\x06\x57\x12\xdb\x97\x76\xbd\x79\xd6\x70\x30\ -\x6b\xac\x08\xfc\xbd\x04\x2b\xd2\xf8\x68\xae\x1f\x46\x95\x9c\x08\ -\x56\x05\xf7\x83\xd5\xb9\xee\x49\x12\xcd\xc1\xd6\xe0\x74\xea\xb7\ -\xe5\x79\xdb\xc7\x4b\xa0\x2b\x0d\x76\xe6\xfa\x66\xf0\xab\xd6\x6b\ -\xc8\x3d\x53\x82\xe7\xc1\xcb\x0a\xfd\x96\xe0\x71\xf0\x24\x98\x36\ -\xde\x1c\x98\x99\x72\x30\xe5\x00\x0a\x4c\xaf\xe1\xbc\x0d\xb7\xb0\ -\x08\xc7\x2a\xe0\xf5\x98\x8b\x17\x98\x3a\xde\x42\x34\x50\x91\x13\ -\x1d\xc9\xfa\x63\x15\xe7\x4d\xb8\x86\x8d\x38\x52\xd0\x5d\xc6\x0b\ -\x0e\x60\x09\x36\x54\x21\x57\x93\xc0\xab\x94\xf3\x53\xce\xc1\xdb\ -\x82\xe1\x2a\x76\x67\xd1\x85\xc3\x05\x67\x4a\xc4\x0e\x05\x97\x4a\ -\x91\xfc\x5e\x2b\x82\xa3\x12\x21\x28\x82\xa7\xc1\x9b\xe0\x42\xe6\ -\xc3\x89\xc4\xf6\x06\xfd\xc1\xb2\xa0\x33\xb1\xe1\xa0\xaf\x34\xdb\ -\x83\x1d\x89\x75\x07\x77\xf2\xbe\x73\xac\x1c\x68\x29\x85\x2d\x82\ -\x4d\x38\x87\x75\xb8\x88\x53\x09\x0f\x65\x95\xfc\x8e\xa5\xb8\x57\ -\xe3\x61\x6e\xa0\x1d\xbb\xf0\x09\x1b\x8b\x3f\x7b\x57\x25\x3e\xaf\ -\xb4\xf7\x27\x06\x8b\x8c\xc0\xc8\x9f\x51\x2b\x9a\x27\xa0\x12\xf6\ -\x60\x73\x85\xee\x3d\x16\x57\x76\xa9\x1f\x39\xff\xf7\xe8\xcd\x9f\ -\x92\x3e\x7c\x4b\xdd\xe7\x7a\xf6\x82\x9a\xf9\xd7\xf0\x0f\x92\x96\ -\x4c\x9a\x46\x8d\xf6\xdf\x9b\x7c\xd8\x9a\x14\x52\xb6\xaa\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xd9\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x04\x56\x49\x44\ -\x41\x54\x58\x85\xbd\x97\x5f\x4c\x53\x57\x1c\xc7\xbf\xe7\xde\xdb\ -\x52\xdb\x52\x23\x0b\x42\x33\x5b\xca\x0b\x84\x0c\x27\x1a\x97\x2d\ -\xc0\x4c\x9c\x9a\x91\x91\xcc\xe0\x74\x0f\x23\xcb\x34\x10\x33\x84\ -\x45\x36\x4d\x60\x7f\x79\xd9\xb2\x3f\xc9\xc2\x03\x8e\xa0\x59\x32\ -\x43\xf6\xb0\x2d\x53\x16\xe0\xc5\x81\x92\x90\x95\x6d\x8a\x30\xc1\ -\x52\x84\x02\x02\x49\x2d\x2d\x90\x4a\x68\xf9\x73\x6f\xef\x6f\x0f\ -\xb5\x8a\xa5\x2d\xbd\x2b\xe3\x97\xfc\x72\x72\x72\xce\xf9\x7d\x3f\ -\xe7\x9e\xf3\x3b\xe7\x5c\x06\xc0\x08\xc0\x87\xf8\x8d\x07\x20\x03\ -\x20\x05\x63\xa2\x99\x4e\x00\xe0\x23\xa2\x85\x58\xbd\xde\x3e\x74\ -\xa8\xf8\xc5\xbc\xbc\xca\xd9\xd5\xd5\xdd\xb4\xb2\x02\x49\x92\x44\ -\xbf\x24\xf9\x75\x1a\xcd\xf0\xd4\xf0\xf0\x37\xcd\xdd\xdd\x37\xff\ -\x8b\x3a\x63\x0c\x0c\x80\x21\x1a\x00\x63\x4c\xf3\xf5\xe9\xd3\x3f\ -\x19\x76\xee\x7c\xc5\xec\xf7\xcf\xbe\xa0\x52\x4d\xa4\x6e\xdb\xe6\ -\x01\xf0\x10\x80\xf7\xfa\xe4\x64\x92\x55\x96\xb3\x27\x16\x16\x66\ -\x7c\x2d\x2d\x65\xbf\x10\x05\x14\x02\x18\xa2\x02\x30\xc6\x84\x6f\ -\xcf\x9e\xbd\x99\xae\xd5\x66\x1d\x57\xa9\x26\xd4\x1c\xe7\x05\xe0\ -\x0d\x89\x03\x78\x08\xc6\xbc\x00\xbc\x57\x26\x26\x76\x5c\x1a\x1c\ -\x34\x5d\xeb\xed\x7d\x4f\x29\x00\x17\xad\xf1\x8b\x53\xa7\xbe\x4b\ -\x17\x84\x9c\xb7\x92\x92\x66\xd4\x1c\x27\x02\x58\xeb\x12\x00\x11\ -\x44\x22\x00\xe9\x0d\x8b\xc5\x51\xb9\x67\xcf\x5f\xf9\xb9\xb9\x1f\ -\x2a\x01\x00\x80\x88\x00\x5a\xad\xd6\x28\xe8\xf5\xa5\xc7\x74\xba\ -\x85\xc7\x62\x6b\x85\x01\x11\x8c\x05\xeb\x44\x22\x18\x13\x5f\xb7\ -\x58\xa6\x52\x78\x5e\x7e\x69\xef\xde\xcc\x84\x01\x3e\x29\x2d\xfd\ -\xe0\x79\x8d\x46\xd0\x70\xdc\x6a\x04\xf1\x27\xe5\x5a\x08\x40\x6a\ -\x3f\x71\xa2\x75\xd1\xe7\x7b\x33\x61\x80\xc5\xa5\xa5\xfc\x03\x2a\ -\x95\x3f\xa2\x68\xa8\x24\x12\x43\xb3\x07\x20\x41\x96\x45\x04\x02\ -\x22\x2f\xcb\xea\x84\x01\x64\x51\xd4\x69\xd5\xea\x70\xd1\x27\xce\ -\xd8\xd3\x4b\xc0\x71\x41\x07\xa4\x67\x2d\x96\xf4\xc4\x01\x02\x81\ -\xe5\x75\xa2\xe1\xb3\x5f\xbb\x04\xb2\x1c\x2c\x05\x41\x64\x2a\x15\ -\xcf\x18\xe3\x13\x02\x70\xba\x5c\xc3\xeb\x44\xe3\x81\x90\x24\x51\ -\x26\x92\x49\xc1\x79\x10\x11\xa0\x7f\x7a\xfa\xea\xdf\xf3\xf3\x81\ -\x88\xe2\x8c\x49\x8f\x97\x20\xb4\x0f\x38\x4e\x04\xcf\x8b\xd5\xb7\ -\x6e\x65\x98\xcc\x66\x7d\xbc\xe2\x51\x01\x6c\x93\x93\xad\xcd\xfd\ -\xfd\x83\x88\x94\x7e\x21\xd1\xf0\xd9\x33\x26\x21\x33\xb3\x62\x68\ -\x68\xe8\xc7\x84\x01\x00\xe0\x4f\xa7\xf3\xfb\x2b\xf7\xef\x13\xc2\ -\xf7\x41\x58\xea\x85\x36\xdf\x99\xbe\xbe\x03\x4b\x4b\x4b\x6a\xab\ -\xd5\xda\xb1\x29\x00\x7d\x0e\x47\xfb\x0f\x03\x03\x6d\x3f\x4f\x4d\ -\xa5\x20\x56\xfe\xcb\xb2\xf8\xbe\xc3\x51\xfa\x4c\x76\x76\xf9\x5d\ -\xbb\xbd\x8e\x88\x14\xdd\x92\x42\xac\xc6\xf6\xdb\xb7\xbf\x3c\x79\ -\xf4\x28\x7f\x47\x14\x8f\xbf\x6c\x30\x8c\xbe\x9a\x9a\x3a\xcb\x05\ -\x67\x2e\xfa\x25\x29\xd0\x30\x3d\x5d\xe0\xdf\xb5\xeb\xdd\x94\xac\ -\x2c\xa3\xd3\xe9\xfc\xd8\x6a\xb5\x8e\x29\x11\x07\x10\xfb\x36\x0c\ -\x99\x9e\xb1\xd4\x8a\xf2\xf2\x4f\x03\x44\x05\x04\x70\x3c\xc7\x49\ -\x01\x9e\xd7\xe8\xb4\x5a\xfb\x82\x28\x16\xef\xdb\xb7\x5f\xb3\x7d\ -\x7b\x72\x7f\x49\x49\xc9\x7e\x45\xe2\x8c\x19\xf0\x08\x00\xf1\x3a\ -\x82\x0f\x12\x4d\xa8\x9e\x9f\x5f\x58\x76\xe1\x42\x23\xdd\xb8\xd1\ -\x45\x4d\x4d\x4d\x95\x0a\x63\x45\xbf\x0d\xa3\x19\x11\x05\x88\x68\ -\x39\x54\xef\xe9\xf9\xe3\xb2\xcd\x66\xeb\x9f\x9b\x9b\x83\xd9\x9c\ -\x71\xbe\xae\xae\x4e\xab\x24\x9e\x62\x80\x48\x40\x36\xdb\x50\xa3\ -\xdb\xed\x81\x5e\xaf\xb7\xe4\xe4\xe4\x7c\xb4\xa5\x00\x00\xd0\xdd\ -\xdd\x75\x79\x70\x70\x60\xc0\xed\xf6\xc0\x68\x34\x9e\xa9\xad\xad\ -\x35\x6f\x29\x00\x11\x49\xf7\xee\x8d\x34\x7a\x3c\x1e\xf0\xbc\xb0\ -\xa3\xb0\xb0\xf0\xb3\x78\xc7\x3e\x95\x05\x8c\xb1\x77\x00\x6c\xf4\ -\xa0\x90\x88\xe8\xf3\x75\x81\x18\xe3\x2b\x2a\x2a\xff\x39\x72\xe4\ -\x70\x6e\x46\x46\xc6\x4a\x47\xc7\xef\x85\x35\x35\x35\xbd\x31\xc5\ -\xc3\xb3\x00\x40\x17\x82\xcf\xed\x58\xbe\x1c\x6d\x57\x1f\x3c\x78\ -\xb8\xf2\xe2\xc5\x4b\x64\xb5\xf6\x50\x67\xe7\xf5\xf6\xff\x25\x0b\ -\x62\x59\x57\x57\x67\x93\xdd\x6e\xb7\x7b\x3c\x1e\x98\x4c\xa6\xd7\ -\xea\xeb\xeb\x8f\x6d\x34\x26\xfc\x24\xfc\x15\xc0\x9d\x0d\xc6\x88\ -\xd1\x1a\x88\x28\x50\x5c\x5c\xdc\xf8\x5c\xee\xee\x86\xb4\xf9\x79\ -\x56\x50\x50\x50\xcb\x18\x6b\x25\x22\x29\x56\x40\x45\x07\x51\x1c\ -\x9f\x55\xa8\xae\x3e\x37\x7a\xb5\xe5\x37\x1a\x1f\x1f\xa7\xe6\xe6\ -\xe6\xa8\x87\x13\x36\x7b\x09\x1e\x7d\x05\x69\x6c\x6c\xb4\xd1\xed\ -\xf6\x60\x66\xc6\x8d\xbc\xbc\xbc\x73\x45\x45\x45\x86\x68\xfd\x37\ -\x1d\x00\x00\xda\xda\x5a\x1b\x46\x46\x46\xc7\x1e\xb8\x5c\x48\x4e\ -\x36\x64\x56\x55\x55\x9d\xdf\x52\x00\x22\x92\x1c\x63\x8e\x26\x8f\ -\x67\x16\x0f\x5c\x2e\xa4\xa5\xa5\x95\x31\xc6\x22\x6a\xc5\xbc\x8e\ -\x13\xb1\xa1\xbb\x03\x0d\x66\x93\xe9\xa4\xdf\xb7\xe8\x5d\x5d\x5d\ -\xf9\x8a\x88\xe4\x48\xfd\x18\x94\xff\x9e\x2b\x31\x01\xc1\x87\x4c\ -\x34\xd3\xfd\x0b\xc3\x01\x11\x2b\xdf\xcb\xac\xe8\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x98\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x03\x15\x49\x44\ -\x41\x54\x58\x85\xc5\x97\x4d\x48\x54\x51\x14\xc7\x7f\xe7\xbd\xa7\ -\x46\x9a\x84\x09\xd1\x2a\x23\x02\xdb\x84\x90\x3a\x93\x05\x7d\x2c\ -\xfb\xda\xf4\xb5\x2b\x8a\xc2\x55\x05\x15\x61\xcb\x20\x42\x10\x0c\ -\xa1\x5d\x5f\x9b\xa2\xc0\x28\x8a\x76\x05\x05\x61\xa8\x19\x06\x81\ -\x2e\x2a\x35\xa2\x0f\x6b\x51\x59\x4e\x33\xe9\x7b\xa7\xc5\x7d\xa3\ -\x8f\xc1\xde\x5c\xc7\x91\x0e\x5c\xe6\x7e\x9c\xfb\xbf\xff\x7b\xcf\ -\xff\x9e\x77\x47\x80\x65\xc0\x38\xff\xc7\xca\x3d\x60\x5c\x55\xc7\ -\x66\x33\xab\x27\x99\x5c\x15\x38\x4e\xc5\xba\x67\xcf\xfa\x01\x5e\ -\xd4\xd7\x97\xf8\xae\xbb\xc5\xf5\xfd\xa7\x6b\xfb\xfa\x52\xb6\x38\ -\x22\x82\x33\x4b\xc6\x00\x38\x41\x90\x76\x82\xe0\xc1\xf3\xc6\xc6\ -\x3a\x80\x49\xcf\x3b\xaf\x22\x07\x67\xb3\xf8\x14\x96\x05\x4b\x57\ -\x44\x6e\x88\x48\x6d\xb6\xaf\xa1\xb7\xf7\xbd\xa8\x36\x07\x8e\x73\ -\xab\x27\x99\xdc\x0d\xec\x9c\xf4\xbc\x23\x91\x39\x55\x22\xd2\x29\ -\x22\x4b\x6c\x48\x54\xaa\x2a\x71\x05\x18\x03\x2e\xe5\xf6\x77\x27\ -\x12\x17\xba\x13\x89\x89\xde\x86\x86\xba\x1c\xff\x16\x40\x81\x45\ -\x79\x70\x2b\x6d\x43\xf0\x09\xd8\x2f\x22\x55\xd9\x8e\x27\x9b\x37\ -\x7b\x40\x3d\xf0\xc5\x77\xdd\x86\xc8\xee\x3d\xe0\x24\x46\x5b\x3f\ -\xf3\x01\xdb\x12\x18\x02\x4a\x81\xe6\x6c\xc7\xc2\x54\xea\x1c\x30\ -\xea\xbb\x6e\x93\xa8\x9e\xed\x49\x26\xd7\x84\x43\x7b\x80\x6a\xe0\ -\x83\x0d\xb0\x2d\x81\xc1\xf0\xf7\x84\x88\x94\xf4\x24\x93\x5b\x55\ -\x64\x5f\x59\x26\x73\xb8\xa9\xab\xeb\x1d\x70\x0c\xe8\xec\xda\xb0\ -\x61\x11\x70\x26\x42\xba\x68\x04\x86\x81\xdf\x40\x05\xb0\xc7\x09\ -\x82\x8f\xbe\xeb\x6e\xaa\xeb\xef\xff\x0e\x90\xe8\xee\xbe\x0d\x1c\ -\x38\x33\x30\xb0\x11\x58\x0d\x04\x11\xd2\x79\xcd\x46\x84\x3b\x80\ -\x5f\x21\xf0\xab\x18\xbf\x7b\xc0\x24\x90\x02\x8e\x5a\xe0\x5a\x8b\ -\x70\x18\x28\x03\x04\xa8\x15\x91\xf5\xb9\x0e\x22\xb2\x1c\xd8\x06\ -\xb8\x98\x1b\x30\x6c\x03\x6c\x4b\x60\x04\xf0\x22\xed\xd3\x33\xf8\ -\x1c\xc7\xec\x9e\x90\xec\x88\x25\x76\xfe\x10\x84\xc7\xf5\x13\xb3\ -\x33\x0d\x17\x5a\x1e\x19\xab\xc0\x1c\xbb\x46\x4a\x85\x4d\x08\x3c\ -\x00\x11\xb9\x8b\x11\x4f\x9c\x95\x46\xea\x0e\xd0\x06\xec\x0d\xdb\ -\x2d\xc0\x82\xc8\x78\x00\xf4\x89\x48\x1c\xde\x57\x4c\xc8\xa8\x04\ -\x5e\xe6\xb0\xb7\x29\xe9\x70\xe7\x0e\x30\x5a\xc0\xfc\xcf\x53\x27\ -\x50\xa0\x09\x70\x08\x13\xeb\xc5\x85\x82\xcc\x85\x40\x29\xb0\x1d\ -\x93\x70\xdc\x42\x41\x0a\xfa\x1c\x87\x36\x01\x5c\x02\xae\xcc\x01\ -\x63\x4e\x27\x30\x0e\xdc\x51\x55\x5f\x44\x5e\x03\xb5\xf9\x26\xc4\ -\x11\xb8\x8f\x11\x62\x9c\xed\xc2\x88\x0e\xc0\x07\xae\xaa\xaa\x1f\ -\xb6\x3b\x80\x8b\x4c\x87\xc2\x07\xae\xe7\xc1\xfb\x91\xad\xd8\xe6\ -\x81\x34\xd3\x0a\xfe\x0d\x2c\x8e\x8c\xb9\x18\x55\x47\x55\x5e\x5d\ -\xb4\x54\x2c\x22\xd5\x98\xec\x06\x90\x01\xae\xa9\xea\xf7\xec\x78\ -\x78\x12\x6d\x21\x31\x30\xfa\xa8\xb1\xc1\xb6\x15\x61\x0d\xf0\x27\ -\xac\x97\x00\xed\x33\xf8\x5c\x8e\xe0\xcd\x0b\x81\x09\x4c\x6c\x1f\ -\xa9\xea\x9b\x5c\x07\x55\xfd\x81\xb9\x11\x99\x10\xb7\xe8\x04\x3c\ -\x4c\x8a\x6d\x8d\xf1\x6b\xc7\x9c\xd0\x02\x60\x65\x31\x09\xac\xc4\ -\x68\x60\x48\x55\x1f\xff\xcb\x49\x55\xdf\x02\x0f\xc3\xa6\xd5\xb5\ -\xb4\x25\x90\x05\x8b\xdb\x7d\xd6\xb2\x3e\x2b\x2c\xb1\xad\x5e\x44\ -\x23\xc0\x37\xa0\xcc\xf2\xca\x0e\x02\xe9\x62\xbe\x88\x96\x02\x1d\ -\xaa\x9a\xb1\xf4\x6f\x05\xca\xc2\xeb\x1b\x6b\x79\x53\xb1\x88\x38\ -\xc0\x29\xa0\xd3\x72\x71\x80\x9b\x40\x15\xd3\x79\xe1\xdf\xf8\x98\ -\x10\xcc\xea\xcf\x69\xb1\x4c\x44\x2a\x3d\xa0\x3c\xcf\xcb\x65\x3e\ -\xad\xfc\x2f\xeb\xa8\x35\x42\x7e\xaf\x56\x1c\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x05\x04\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x04\x81\x49\x44\ -\x41\x54\x58\x85\xbd\x97\x5d\x4c\x93\x57\x18\xc7\xff\xcf\xfb\xb6\ -\x50\xdb\x5a\xa3\x0b\x56\x50\x6a\xd9\x05\x84\x4c\x67\x35\x98\x2d\ -\xc0\x5c\xa2\x59\x34\x61\x9b\xd1\xe9\x2e\xc6\x96\x68\x20\xcc\x0f\ -\x16\x61\x7a\xc1\x3e\xd9\xcd\xa2\x2c\x99\x17\xc3\x11\xb2\x98\xcc\ -\xb0\x5d\x6c\x4b\x44\x04\x6f\x96\x45\x59\xc8\xea\xa6\x28\x64\xe5\ -\x1b\x0a\x08\x24\x50\x5a\x20\x95\x40\x11\xde\x8f\x67\x17\xa5\xda\ -\xd5\x16\xfa\x8a\xe1\x49\x4e\x4e\x4e\xcf\x79\xdf\xff\xef\x79\xcf\ -\x79\x9e\xe7\x94\x00\x24\x03\x98\x45\xfc\x26\x02\x50\x01\xb0\x86\ -\x67\x62\x99\x49\x07\x60\x96\x99\xa7\x97\x5a\xf5\xc1\xbe\x7d\x79\ -\xaf\x38\x1c\xa7\x27\x16\x16\xb6\xf3\xfc\x3c\x64\x59\x96\x02\xb2\ -\x1c\x30\x19\x0c\xdd\xc3\xdd\xdd\xdf\xd4\x34\x35\xdd\x7d\x16\x75\ -\x22\x02\x01\xb0\xc4\x02\x20\x22\x43\x45\x51\xd1\x2f\x96\x8d\x1b\ -\xf7\xda\x02\x81\x89\xdd\x7a\xfd\x60\xd2\x9a\x35\x3e\x00\x0f\x01\ -\xf8\x6f\x0e\x0d\x25\x3a\x55\x35\x63\x70\x7a\x7a\x7c\xf6\xda\xb5\ -\x82\xdf\x98\x15\x8d\x00\x96\x98\x00\x44\xa4\xfb\xf6\xcc\x99\xbb\ -\x9b\x8c\xc6\xf4\x23\x7a\xfd\x60\x82\x20\xf8\x01\xf8\x43\xe2\x00\ -\x1e\x82\xc8\x0f\xc0\x7f\x75\x70\x70\xfd\x0f\x6d\x6d\xa9\xbf\xdf\ -\xbb\xf7\x91\x56\x00\x21\xd6\xe4\xd7\xc7\x8f\x7f\xbf\x49\xa7\xcb\ -\x7c\x2f\x31\x71\x3c\x41\x10\x24\x00\xe1\x4d\x06\x20\x81\x59\x02\ -\x20\xbf\x63\xb7\xbb\x4f\xef\xd8\xf1\x4f\xf6\xb6\x6d\x9f\x68\x01\ -\x00\x80\xa8\x00\x46\xa3\x31\x59\x67\x36\xe7\x1f\x36\x99\xa6\x1f\ -\x8b\x85\x0b\x03\x12\x88\x82\x63\x66\x09\x44\xd2\xdb\x76\xfb\xf0\ -\x06\x51\x54\x5f\xdd\xb9\x33\x6d\xc5\x00\x9f\xe7\xe7\x7f\xfc\xb2\ -\xc1\xa0\x33\x08\xc2\x42\x14\xf1\x27\x7d\x38\x04\x20\xdf\x38\x7a\ -\xb4\x7e\x66\x76\xf6\xdd\x15\x03\xcc\xcc\xcd\x65\xef\xd1\xeb\x03\ -\x51\x45\x43\x3d\xb3\x14\xf2\x1e\x80\x0c\x55\x95\xa0\x28\x92\xa8\ -\xaa\x09\x2b\x06\x50\x25\xc9\x64\x4c\x48\x88\x14\x7d\xd2\x88\xfe\ -\xbf\x05\x82\x10\x6c\x80\xbc\xd9\x6e\xdf\xb4\x72\x00\x45\x79\xf4\ -\x94\x68\xa4\xf7\xe1\x5b\xa0\xaa\xc1\x5e\xa7\x93\x48\xaf\x17\x89\ -\x48\x5c\x11\xc0\xa8\xc7\xd3\xfd\x94\x68\x3c\x10\xb2\x2c\xa9\xcc\ -\x2a\x6b\xc8\x07\x51\x01\x5a\x47\x46\x6a\xef\x4c\x4d\x29\x51\xc5\ -\x89\xe4\xc7\x5b\x10\x3a\x07\x82\x20\x41\x14\xa5\x92\xe6\xe6\xad\ -\xa9\x36\x9b\x39\x5e\xf1\x98\x00\x1d\x43\x43\xf5\x35\xad\xad\x6d\ -\x88\x16\x7e\x21\xd1\x48\xef\x89\x64\xa4\xa5\x9d\xec\xec\xec\xfc\ -\x79\xc5\x00\x00\xf0\xf7\xe8\xe8\xe5\xab\x0f\x1e\x30\x22\xcf\x41\ -\x44\xe8\x85\x0e\xdf\xa9\x96\x96\x3d\x73\x73\x73\x09\x4e\xa7\xf3\ -\x8f\xe7\x02\xd0\xe2\x76\xdf\xf8\xd1\xe5\x6a\xf8\x75\x78\x78\x03\ -\x96\x8a\x7f\x55\x95\x4a\xdd\xee\xfc\x17\x32\x32\x0a\xdb\xbb\xba\ -\xca\x99\x59\x53\x95\xd4\x2d\x35\x79\xe3\xfe\xfd\xf3\xc7\x0e\x1e\ -\x14\xff\x95\xa4\x23\xaf\x59\x2c\x7d\xfb\x93\x92\x26\x84\xa0\xe7\ -\x52\x40\x96\x95\xca\x91\x91\x9c\xc0\x96\x2d\x27\x36\xa4\xa7\x27\ -\x8f\x8e\x8e\x7e\xe6\x74\x3a\xfb\xb5\x88\x03\x58\xba\x1a\x86\xcc\ -\x4c\x94\x74\xb2\xb0\xf0\x0b\x85\x39\x87\x01\x41\x14\x04\x59\x11\ -\x45\x83\xc9\x68\xec\x9a\x96\xa4\xbc\x5d\xbb\xb2\x0c\xeb\xd6\xad\ -\x6d\x3d\x74\xe8\x50\x96\x26\x71\x22\x0b\x16\x01\x10\x6f\x43\xf0\ -\x42\x62\x08\x8d\xb3\xb3\x73\x0b\x2e\x5d\xaa\xe2\x5b\xb7\x1a\xb9\ -\xba\xba\xfa\xb4\xc6\x77\xc5\xae\x86\x8b\x84\x6f\x11\xd1\x9f\x44\ -\x54\x14\xfa\x8d\x99\x15\x66\x7e\x14\x1a\xdf\xbe\xfd\xd7\x95\x8e\ -\x8e\x8e\xd6\xc9\xc9\x49\xd8\x6c\x5b\xcf\x95\x97\x97\x1b\xb5\x7c\ -\x85\x25\x01\x00\xa4\x00\x78\x1d\xc0\x8b\xb1\x16\x30\xb3\xd2\xd1\ -\xd1\x59\xe5\xf5\xfa\x60\x36\x9b\xed\x99\x99\x99\x9f\x3e\x4f\x80\ -\xb8\xac\xa9\xa9\xf1\x4a\x5b\x9b\xcb\xe5\xf5\xfa\x90\x9c\x9c\x7c\ -\xaa\xac\xac\xcc\xb6\xaa\x00\xcc\x2c\xf7\xf4\xf4\x56\xf9\x7c\x3e\ -\x88\xa2\x6e\x7d\x6e\x6e\xee\x97\xab\x0a\x00\x00\x8d\x8d\x37\x2f\ -\xbb\x5c\xae\x76\x9f\xcf\x87\x94\x94\xcd\xef\x57\x54\x54\xc4\x15\ -\x11\x8f\xf3\x00\x11\x1d\x01\xf0\x66\xc4\x7c\xfa\x62\x9f\x47\x44\ -\x91\x65\xb6\x85\x99\xbf\x0b\x0d\x98\x59\xd9\xbb\xf7\x8d\x6a\x87\ -\x63\xc7\x25\xab\xd5\x9a\x98\x95\xb5\xfb\xab\x28\xef\x8b\x6a\x96\ -\xc5\x90\x38\x8f\xe0\x5d\x3f\xde\x56\x17\x2d\x44\x4b\x4a\x4a\x3b\ -\xeb\xea\xae\x73\x4f\x4f\xaf\x7a\xf1\xe2\xc5\xc3\xcb\x85\x61\x78\ -\x26\xfc\x09\xc0\x9d\x08\xb8\xfd\x00\x4e\x00\xa8\x5d\x9c\x0f\xb7\ -\xb1\x48\x4f\x98\x59\xc9\xcb\xcb\xab\x7a\x69\xdb\xf6\x4a\xeb\xd4\ -\x14\xe5\xe4\xe4\x94\x11\x51\x3d\x33\xcb\xcb\x7e\x81\x18\x84\x1f\ -\x2e\x7a\x7b\x41\x43\x72\xd1\x95\x94\x9c\xed\xab\xbd\x56\xc7\x03\ -\x03\x03\x5c\x53\x53\x13\x33\x39\x61\xb9\x44\xf4\x2c\xc6\xcc\x72\ -\x7f\x7f\x5f\x95\xd7\xeb\xc3\xf8\xb8\x17\x0e\x87\xe3\xec\x81\x03\ -\x07\x2c\xb1\xd6\x3f\x77\x00\x00\x68\x68\xa8\xaf\xec\xed\xed\xeb\ -\x1f\xf3\x78\xb0\x76\xad\x25\xad\xb8\xb8\xf8\xdc\xaa\x02\x30\xb3\ -\xec\xee\x77\x57\xfb\x7c\x13\x18\xf3\x78\x60\xb5\x5a\x0b\x88\x28\ -\xaa\xd6\x92\xe5\x18\xc0\x6d\x00\xa5\x00\x9a\xb5\x42\x74\xb6\xbb\ -\x2a\x6d\xa9\xa9\xc7\x02\xb3\x33\xfe\x85\x85\xf9\x0b\xcc\xac\x46\ -\x5b\x47\xd0\xfe\xf7\x5c\x8b\xe9\x10\xbc\xc8\xc4\x32\xd3\x7f\x2a\ -\xd9\x02\x8c\x40\x79\xbc\x6b\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x04\x38\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x03\xb5\x49\x44\ -\x41\x54\x58\x85\xed\x97\xcf\x6b\xe3\x46\x14\xc7\xdf\xbc\x19\x4b\ -\x4d\x64\x4b\xc8\x75\x8c\x13\xe7\x27\xa1\x05\xe7\x52\x4a\xe9\xaf\ -\x5b\x20\x87\x2e\xed\x39\x2c\x85\x92\x5b\xc1\x01\x97\x9e\x7b\x59\ -\x72\xe8\x1f\x50\x12\x7a\x28\x14\x4a\xaf\xa1\xe7\x5e\x9a\x5b\xa1\ -\x29\xb4\xa6\x14\x1f\x0c\x8e\xe9\x6a\xd9\xc4\x89\x8c\xfc\x23\x5e\ -\x54\xd9\xd6\x48\xd3\xc3\x5a\xc1\x76\x64\xbb\x0e\x31\xb9\xec\x03\ -\x21\xf4\xe6\x3b\xef\xfb\x99\xd1\x68\x24\x11\x00\x58\x04\x00\x1b\ -\x1e\x26\x14\x06\x00\xb6\x10\xa2\xf5\x10\xee\x84\x10\x60\xfd\x89\ -\xfd\xfd\xfd\xb7\x63\xb1\xd8\xd7\x92\x24\xcd\xcc\xb4\xd5\x6a\x15\ -\x8e\x8e\x8e\xbe\x12\x42\x08\x00\x18\x04\x58\x5f\x5f\xff\x3e\x97\ -\xcb\xbd\xc6\x39\xbf\x9c\x85\xb9\x10\x02\xcf\xcf\xcf\x1f\x71\xce\ -\x8b\x00\xf0\xe3\x2d\x80\x64\x32\xe9\x35\x9b\xcd\x3f\x4a\xa5\xd2\ -\x6f\xb3\x00\x00\x00\xc8\x64\x32\x5f\x20\xa2\x16\x5c\xb3\x71\xe2\ -\x51\xe1\xfb\x3e\x39\x39\x39\xf9\x4c\xd3\xb4\xa7\x6b\x6b\x6b\xc5\ -\x30\x4d\xb9\x5c\x7e\xa7\xd3\xe9\xa8\x3b\x3b\x3b\x3f\x8d\xab\x75\ -\x27\x00\xce\x39\xbb\x6e\x34\xde\x8d\x5b\x96\xda\x3d\x3b\x5b\x0a\ -\xd3\x20\x62\xba\xc1\xd8\x1a\x00\xdc\x3f\x00\x63\x8c\xeb\x94\x3e\ -\xfb\xb4\x5e\xff\x7d\x94\xc6\x25\xe4\xe9\x77\xc9\x24\x4e\xaa\x35\ -\x51\x10\xda\x09\x51\xc4\x11\xaf\xc6\x69\x22\x42\xf8\xba\x24\x3d\ -\x9f\x09\xc0\x7d\xc6\x2b\x80\x57\x00\x77\x02\x70\x5d\x97\x3d\x73\ -\xdd\xb7\xc6\x69\x6c\x42\x22\xcf\x6d\xfb\xfd\x49\xb5\xee\xb4\x0f\ -\x00\x00\x70\x00\xf9\x9b\x44\xe2\x93\x04\x63\x46\x58\xbb\xc9\xf9\ -\x9b\x00\xe0\xcf\x04\x20\x12\x89\xf0\xdd\xc7\x8f\xbf\xbc\x4b\xdf\ -\xb1\x00\x42\x08\x70\x5d\x97\x74\xbb\xdd\x9b\x5b\x83\x88\xa2\x77\ -\x86\xe1\xdc\xbd\x03\x38\x8e\x43\x4b\xa5\x92\x52\x28\x14\xf4\xc0\ -\x90\x10\x12\x00\x0c\x80\x04\xf9\xfe\xa0\x94\x0e\x68\xfb\x23\xd0\ -\xa7\x52\x29\x3a\x12\xa0\xdd\x6e\xa3\x61\x18\xf3\x86\x61\xe8\x7d\ -\xc6\x23\x0d\x03\xa3\xe1\xb6\x00\x24\x0c\x60\x6b\x6b\x6b\x34\x40\ -\xa7\xd3\xc1\x66\xb3\xa9\x5c\x5e\x5e\xea\xc3\x45\xfb\x47\x35\xae\ -\xad\x17\xb7\xb4\xc1\x40\x2c\xcb\x1a\x0d\x50\xaf\xd7\xa9\x24\x49\ -\x6f\xa4\xd3\xe9\xc4\x70\xb1\xbe\x99\x18\x1e\xdc\x2d\x80\x40\x13\ -\x92\x27\xa6\x69\x12\x00\xf8\x37\x14\xe0\xfa\xfa\x3a\x57\xab\xd5\ -\x8e\xda\xed\x76\x24\xcc\x28\x08\x4a\x69\x1c\x00\x68\xff\xc2\x04\ -\x00\xf0\x7d\xff\x85\x10\xc2\x19\xd5\x57\x92\x24\xaf\x56\xab\xfd\ -\xda\x6a\xb5\x7e\xb8\x81\x02\x00\x75\x9a\xaf\xe2\x6c\x36\xfb\xb1\ -\xae\xeb\xdf\x2a\x8a\x12\x19\x6e\xab\x56\xab\xe5\xc3\xc3\xc3\xed\ -\xff\x5b\x8b\x10\xa2\x4e\xb5\x13\xe6\x72\xb9\xd7\x65\x59\x7e\x12\ -\x8b\xc5\x28\x22\xfa\xc3\x87\xa2\x28\xeb\xd9\x6c\xf6\xd1\x34\x35\ -\x27\xce\xc0\xde\xde\x9e\x12\x8d\x46\x3f\x44\xc4\xcf\x19\x63\xef\ -\x69\x9a\x36\x47\x29\x1d\xb9\xc3\x35\x1a\x0d\xcf\x75\xdd\x7f\x00\ -\xe0\x17\xd7\x75\x7f\x6e\x34\x1a\x7f\x1f\x1f\x1f\x7b\xa1\xe6\x84\ -\xa8\x13\x77\x42\x59\x96\x37\x11\xf1\x03\x42\xc8\x5f\xbe\xef\xff\ -\x59\xaf\xd7\x09\x22\x82\x10\x82\x20\x22\x01\x00\xf0\x7d\x7f\xe0\ -\x71\xec\x2d\xbe\x08\xa5\xf4\xa3\x58\x2c\x76\x06\x00\x2f\xa6\x99\ -\x01\x92\xcf\xe7\x59\xb7\xdb\x65\xc5\x62\x91\x55\xab\x55\x56\x2a\ -\x95\x58\xa5\x52\x61\x17\x17\x17\xcc\xb2\x2c\x7a\x75\x75\x45\xe1\ -\xe5\x8b\x2c\xb8\x85\x02\x00\x84\x2c\xcb\xfe\xd2\xd2\x12\x4f\x26\ -\x93\xde\xea\xea\x2a\xd7\x75\x9d\x67\x32\x19\x9e\x4e\xa7\xf9\xc2\ -\xc2\x02\x07\x00\xbe\xbd\xbd\xcd\xfb\x67\x60\x18\x00\xcb\xe5\x72\ -\xe4\xf4\xf4\x94\x39\x8e\xc3\x0c\xc3\x60\x86\x61\x30\xd3\x34\x99\ -\x61\x18\xb4\x52\xa9\xb0\x76\xbb\x1d\x98\x93\x61\x00\x78\xf9\xf2\ -\xf1\x35\x4d\xf3\x56\x56\x56\xf8\xe2\xe2\xa2\x97\x4a\xa5\xf8\xe6\ -\xe6\x26\x8f\xc7\xe3\x7c\x63\x63\x83\x47\xa3\xd1\x6e\x00\x11\x06\ -\x10\x04\xe6\xf3\x79\x5a\x28\x14\xa8\x65\x59\xd4\xb6\x6d\x6a\x9a\ -\x26\xb5\x2c\x8b\xd9\xb6\x4d\x5d\xd7\x45\xcf\xf3\x88\xe3\x38\x37\ -\x1d\xa2\xd1\xa8\x40\x44\x31\x3f\x3f\xef\xc5\xe3\x71\x9e\x48\x24\ -\xbc\xb9\xb9\x39\x4f\x55\x55\x6f\x79\x79\xd9\x03\x00\x6f\x77\x77\ -\x77\x60\x2d\x10\x42\x54\xe8\x01\xc0\x34\x07\x00\x10\x21\x04\x11\ -\x42\xe0\xc1\xc1\x01\x0a\x21\x48\x2f\x37\x6d\x1d\x95\xc0\x03\xff\ -\x9e\xff\x07\xb7\x67\xdf\x28\x63\xab\x1b\xbf\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x07\x10\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x06\x8d\x49\x44\ -\x41\x54\x58\x85\xc5\x57\x7b\x50\x94\xd7\x15\xff\xdd\x6f\x17\x16\ -\x76\xd7\x25\xcb\x12\x1e\x51\xd6\x00\x85\x0c\x6c\x01\xa3\x01\xed\ -\x88\x1a\x69\xda\x0a\xca\x4c\x0d\x3a\x36\xb6\xb4\x4e\x12\xc1\xa0\ -\x93\x32\x69\xfe\x50\xec\x4c\x64\x3a\x2d\x49\xa7\x63\x92\xd1\xc1\ -\xec\x42\x3b\x49\x99\xa4\x2a\xe3\x68\x1c\x93\x38\x68\xc2\x84\x04\ -\x34\x12\x1e\x2a\x8f\x40\xe5\x21\x8f\x7d\xc8\x22\xbb\xc0\x2e\x2c\ -\xfb\x7d\xdf\xe9\x1f\xb2\xce\xba\xb0\xbb\x89\x69\xd3\xdf\xcc\x9d\ -\x6f\xee\xb9\xe7\x9e\xdf\xb9\xe7\x9c\x7b\xee\x7c\x0c\x40\x1c\x00\ -\x07\xfe\x3f\x50\x48\x01\x38\x88\x68\xea\xdb\x68\x33\xc6\x42\xb2\ -\xf3\x4a\x7f\xb3\xe6\xa9\xf4\x3c\x65\x28\x8b\x9e\x76\xcc\x4e\xf3\ -\xee\xb9\x91\xdb\xfd\xb7\xce\xd5\x9f\xad\xa9\xff\xae\xec\x8c\x31\ -\x30\x00\x2a\x6f\x07\x18\x63\x91\x00\x8e\x03\x90\x2f\x88\x46\x01\ -\xfc\x3e\xaf\xe8\x8f\x07\x92\x57\x6a\x0e\xc9\x54\x71\xd2\xb1\xa9\ -\x30\x8b\xc5\x29\x37\x2a\x64\x9c\x53\x46\x53\xc4\x9c\xc3\xf2\x69\ -\x63\x27\x6f\x9f\x9a\x39\xdc\x5c\x7f\xb2\x00\xc0\xea\x85\xbd\x3c\ -\x80\x57\x89\x68\xc8\x8f\x03\x2a\xa9\xaf\x90\x88\xee\x32\xc6\x4e\ -\x03\x38\x03\x80\x03\x80\xc7\x1e\x4f\xcd\xd5\x3d\xa1\x7d\xbc\x9f\ -\xcb\x19\x95\xaa\x52\xcd\x88\x80\x4d\x0d\xd8\x71\x6f\xd8\xc0\x60\ -\x93\xc6\x0d\xb8\x8d\xef\x16\xd6\x02\xd0\x79\x99\xdb\xeb\x8f\xdc\ -\x03\x6e\x29\x21\x11\x9d\x03\x70\xc0\x33\x37\x0e\xf5\xa4\xd6\xb7\ -\xdd\x75\x4a\x35\xa9\xd3\x00\xdc\x20\xf0\x8c\xc0\x73\x80\x9b\x00\ -\xb7\x48\xe0\xfb\x1a\x4e\x24\x0e\xf5\x5e\x4f\xf3\x32\x73\x90\x88\ -\x6a\x02\x91\x03\x58\x9c\x82\x07\xbc\xe3\x24\x6f\x12\x89\x65\x00\ -\xc0\x38\x09\xad\xdb\x7b\xaa\x77\xc5\xea\xc2\x61\x22\xd8\x00\xd8\ -\x19\xbb\xf7\xbd\x7d\xe5\x3d\x55\xcb\x3f\x5f\x2c\x23\x91\x0f\x05\ -\x80\xe8\xd8\xc7\xcc\x7f\xaa\x78\xed\x6d\x8f\x1d\x51\x14\xff\xb1\ -\x6f\xdf\xbe\x3b\x8b\xc8\x97\x4a\x81\x37\x76\x1f\xa8\x0c\xb9\xd2\ -\x78\x51\x18\xb8\xde\x20\x21\x51\x60\x2d\xef\xee\x49\x96\xab\xe3\ -\x2d\x91\x09\xd9\x3c\xa3\x7b\x91\xb0\x0e\x7d\xa5\x68\xfb\x60\x7f\ -\x89\x87\x5c\x1d\x1d\xdf\x1b\x97\xbe\xa5\xb2\xf2\x8d\xa3\xd6\xc1\ -\xfe\x6f\x3e\x0a\x16\x81\x25\x53\xe0\x81\xcb\xe5\xca\xc9\x7c\xe1\ -\xfc\xd4\xa3\x29\x9b\x66\x01\x80\x77\xcd\x48\x9a\x4e\xfc\xf2\x29\ -\xc7\xe4\x08\xd7\xff\xc9\xa1\xcd\xdf\x9c\xfa\xdd\xaf\x9b\x8f\xfd\ -\xe2\x15\x7e\xde\x11\x01\x00\xca\x08\x8d\x23\x7d\x5d\x5e\x43\xca\ -\x2e\x43\x93\x20\x8a\x19\xc1\xc8\x83\x3a\x20\x4a\xc2\x95\x52\x99\ -\xd2\xbd\x7e\xff\xf9\x31\x55\x5c\xaa\x13\x00\xe6\xec\x26\xc5\x97\ -\x6f\x6f\x79\x7a\x7e\x66\x3c\x6c\xa8\xe7\x9a\x7b\xce\x61\x97\x01\ -\x40\x98\x2a\xb6\x73\xd5\x33\x2f\x1e\x67\x80\x20\x00\xee\xa8\xa8\ -\x28\xc5\xb7\x71\x20\x60\x0a\x44\x81\x17\x24\x80\x3b\x24\x4c\x35\ -\xbf\xe1\xe5\x8b\x5d\x9f\xbe\xbe\xf6\xc7\x73\x76\x73\xf8\x94\xa9\ -\x3b\xb6\xef\xee\x10\xef\x72\x39\xa5\x00\x20\x53\x46\x0d\x6e\x7c\ -\xe5\xf2\x11\x67\x7b\xd5\x33\xe6\x81\xd6\x7c\xbb\x3e\x27\x53\xad\ -\x52\x44\x18\x0c\x86\x19\xc0\x7f\x0d\x04\x8d\xc0\xc4\xe4\xf4\x28\ -\x00\xbe\xbd\x76\x4f\xc2\x68\xd3\x89\xe4\x95\xab\xf2\x66\x25\x21\ -\x61\x22\x00\x78\xc8\x43\xc3\x1f\xb9\xb3\xbe\xf4\xfc\x9f\x23\x62\ -\x75\x53\xa1\xaa\x15\xdd\x61\xf2\x65\x23\x12\x89\x74\x52\xa1\x90\ -\xdb\x89\xc8\x46\x44\x36\x41\x10\x84\x87\x8a\xc0\xd4\xf8\x60\x5f\ -\x2c\xa0\x95\x29\xa3\xf8\x94\x82\xca\xd6\x59\xdb\x98\xf3\x76\xc7\ -\xc5\x8d\x82\xdd\x14\x71\xdf\x40\xb8\xca\xba\x2c\x2e\x6d\x92\x08\ -\x6e\x71\x76\x42\x1d\x19\xbd\xbc\x5b\x22\x09\x3f\xab\x54\x38\x77\ -\x08\x82\x70\x0e\x00\xac\x56\xab\xfd\xa1\x1c\x18\xbd\xd9\x50\xa5\ -\x49\x7b\x7f\x2d\x48\x7c\xd4\x3d\x6b\x17\x3f\x3f\x9a\xbb\x7e\xce\ -\x8b\x1c\x00\x9c\x77\x87\xd3\x3e\x7f\x7d\xf5\x6b\xab\x7f\xf6\xc2\ -\xc9\xb9\xc9\x91\x24\x59\x28\x67\x49\x4f\x56\x6f\xe9\x68\xed\xbb\ -\x50\x5a\x5a\x6a\x0e\x64\x1f\x08\x92\x02\xab\xd5\x74\xd3\xd8\x56\ -\xf7\x35\x44\x37\x1a\xdf\xfa\xf9\xaa\x69\x4b\x5f\x24\x00\x48\x65\ -\x4a\x47\x46\xfe\xab\x1f\x4b\x43\x64\x6e\x00\xb0\x59\x06\x32\x7a\ -\xbe\xa8\x7d\x4e\x74\xcf\x2c\x9f\x9b\xb6\x6a\x5c\x73\xce\xe8\xc6\ -\xc6\xc6\xf3\xc1\xc8\x3d\x50\x11\x11\xfc\x0d\x00\xcb\x22\x34\x71\ -\x0e\x00\x04\x80\x38\xa9\x6c\x7e\x5d\xf1\x69\xfd\x0e\x3d\x95\x65\ -\x14\xfe\xb5\x92\x31\x8e\xf7\xac\x25\xa7\xad\xf9\xb0\x78\xdf\x4b\ -\x7d\xdb\xb6\x6d\x5b\x17\xc8\xa6\x97\x6d\x55\xc0\x4e\x08\x00\x8c\ -\xb1\x63\x58\x68\xcb\x8c\x71\xf4\xe4\xaf\x8e\x9d\x49\x7a\xba\xb4\ -\x83\x01\x36\x10\xec\x5f\xbe\xb3\x7d\xad\xb1\xe3\xdc\x01\x00\xe0\ -\x38\x0e\xf9\xf9\xf9\x57\x0a\x0a\x0a\x1e\x78\x19\x79\x9e\x7f\x67\ -\xa9\x74\x2c\xea\x84\x15\x15\x15\x5c\x4c\x4c\x8c\xd6\x33\x2f\x2f\ -\x2f\x7f\x19\x5e\x6f\x42\x42\x4a\xfa\x85\x84\x90\xbe\x95\xcb\x4d\ -\x55\x09\x02\x42\x26\x5c\xae\x79\xdb\xf3\x3b\x73\x63\xce\xb8\x6f\ -\x4d\xf6\x74\x75\xaa\x45\x51\x44\x7d\x7d\x7d\xb6\x56\xab\xbd\x9e\ -\x99\x99\x69\xf1\xec\x1b\x1f\x1f\xb7\xfa\x3d\xa0\x77\x04\xea\xea\ -\xea\x42\x6d\x36\xdb\x6e\x00\xa8\xa9\xa9\xd9\x7c\xed\xda\xb5\xdf\ -\x7a\xe9\x1e\x26\xa2\xbf\x30\xc6\xa4\x3f\x4a\x5b\x93\xa3\x4d\x4a\ -\x4d\x8a\xd6\x44\x3c\x32\x7c\x7b\x60\xb8\xb9\xe1\x93\xcb\x1a\x8d\ -\xe6\xdf\x13\x13\x13\x9a\x85\x93\x59\x88\x28\x8b\x88\x46\xfc\x11\ -\x7b\x22\xb0\x64\x0a\x18\x63\x3b\x00\x9c\xc2\x42\x91\xa6\xa4\xa4\ -\x5c\xed\xed\xed\xfd\x89\xb7\x8e\xc1\x60\xf8\x03\x80\x65\x9e\x79\ -\x7b\x7b\x47\x62\x5d\x5d\x5d\xd1\xc4\xc4\xfd\xc3\x76\x02\xc8\x21\ -\x22\xbf\x57\x90\x31\xa6\x02\x7c\x8a\x10\xc0\x4f\x01\xb8\xb0\x50\ -\x58\x00\xce\x56\x55\x55\x1d\xf2\x2d\x20\xbd\x5e\x7f\xd0\x57\xb6\ -\x7d\xfb\xb3\xad\x72\xb9\x9c\xbc\xf6\x7e\x0a\x20\x24\x50\x11\x72\ -\x3e\x1e\xad\x01\x70\x16\x40\xe8\x82\xa8\x19\xc0\x6e\x89\x44\x42\ -\x81\x42\xe9\x81\x56\x1b\x7f\x79\xd7\xae\xe7\x88\xe3\xee\x9b\xcd\ -\x4d\x4c\x4c\xfc\xba\xa2\xa2\xc2\x6f\xbf\x79\x60\x81\x88\x5a\x01\ -\xa8\x7c\x95\xf4\x7a\x7d\x82\xc1\x60\x38\xe2\xcb\xe7\xab\xa7\xd3\ -\xe9\x3e\x6e\x6f\xef\xd8\x56\x5b\xfb\x7e\x5a\x52\x52\x22\xb5\xb5\ -\xb5\xbe\x27\x91\x48\x7a\xd5\x6a\xb5\xdf\x03\x04\xec\x84\x1e\x94\ -\x94\x94\x94\xf8\xca\x0c\x06\xc3\xc1\x25\x54\x23\xed\x76\xfb\x1b\ -\x63\x63\x63\x7f\x8f\x89\x89\x96\x6a\xb5\x5a\x5d\x4b\x4b\xcb\xfe\ -\xe2\xe2\xe2\x87\x7b\x0b\x82\x40\x56\x5d\x5d\xbd\xca\x5b\x40\x44\ -\xb1\x9b\x36\x6d\x6c\x68\x6e\xbe\xfa\x61\x7c\xfc\x8a\x42\x9d\x4e\ -\x97\x35\x38\x38\xb8\x07\x40\x95\x3f\x23\x01\x5b\x71\x10\x9c\x12\ -\x45\x31\xd6\x7b\x60\xe1\x56\xf4\xf4\xf4\xfc\x6d\x6c\xcc\xc8\x5b\ -\xad\x56\x64\x65\x65\x95\x65\x67\x67\x2f\x4a\xab\x07\x41\x3b\xe1\ -\x77\x41\x75\x75\xf5\x76\x51\x14\x07\x64\x32\x59\xef\xd5\xab\x5f\ -\x9d\xde\xbc\x39\xb7\x20\x3d\x5d\x87\xae\xae\xae\x23\x3b\x77\xee\ -\xac\x58\x44\xce\x98\xea\xfb\x44\x60\x11\x44\x51\x9c\x61\x8c\x15\ -\xce\xcf\xcf\x97\x29\x95\x4a\xa3\xd1\x64\x12\x2d\x96\x3b\xc8\xc8\ -\xc8\x28\x2d\x2a\x2a\x5a\xe9\x6f\x5f\xc0\xc7\xe8\xfb\x8c\xbd\xc5\ -\x2f\x5d\xf8\xe0\x5f\x27\xa9\xbb\xbb\x87\x2e\x5d\xba\x74\x3c\x68\ -\x1f\xf8\x6f\xa3\xab\xf3\xe6\x51\x93\xc9\x2c\x98\xcd\x66\x24\x27\ -\xa7\x3c\x5f\x5e\x5e\xfe\xa4\xaf\xce\xff\xd4\x81\xa6\xa6\x2f\x3e\ -\xeb\xee\xee\xbe\x6c\x32\x5b\x30\x3b\xeb\x0c\xdf\xba\x75\xeb\xe1\ -\x1f\xd4\x01\x00\xe8\xbc\x79\xe3\x4d\xb3\xd9\x2c\xdc\xea\x1f\x98\ -\xee\xef\xef\xbf\xe1\xbb\xce\xf0\x03\xfc\x9e\x6f\xd8\xb0\x71\x07\ -\x63\xb8\xd1\xd8\xd8\xd8\xe7\xb3\xa4\xf8\x0f\x57\x7d\x9a\x0c\x52\ -\xb2\x60\x80\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x47\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x01\xc4\x49\x44\ -\x41\x54\x58\x85\xed\x96\xbf\x4b\x5c\x41\x14\x85\xbf\x63\xde\x4a\ -\xa2\xb2\x2a\x8b\xb0\xb1\x51\x10\x24\xfe\x28\x2c\x2d\x6c\x0c\x08\ -\x81\x34\x26\x7f\x81\xa5\xb6\x01\x83\xa5\x9d\x8b\x55\xfe\x09\x41\ -\x6d\xd4\x42\x50\x0b\x21\x45\xc0\xd2\xc2\x22\x45\xc0\x76\x23\x44\ -\x24\x89\x61\x31\xc2\x4d\xf1\x14\x52\xbc\x3b\x6f\xf1\x39\x2b\x88\ -\x07\x5e\xf5\xcd\xdc\x39\xef\xce\xcc\x61\x04\xbc\x04\x2e\x89\xa3\ -\x69\xe0\x3d\xf0\xc3\xe1\x9f\x13\xe0\xd2\xcc\x7e\xc6\x58\x5d\xd2\ -\x0b\xe0\x14\x58\x77\x86\xfc\x49\x62\x2c\xfc\x9f\x1a\x40\xdd\xcc\ -\xbe\x66\x41\x49\xe5\xc2\x06\x24\x4d\x01\x5d\x0e\x1e\xc3\x6f\x3f\ -\x00\xf7\xd1\x81\x55\x60\xd3\x61\xd5\x56\x18\x38\x33\xb3\x4f\x59\ -\x40\xd2\xec\x8d\x89\xa8\x06\x42\x7a\x0e\x54\x25\xbd\x72\x78\xf4\ -\x43\x78\x05\x8c\x00\xf3\x0e\xdf\xcf\x35\x20\x69\x0b\xe8\xbe\x29\ -\x96\xa5\x8e\xc0\xf4\x06\xf0\x37\x54\xbf\x99\x0e\x7c\x07\x16\xcc\ -\xac\xee\x18\xdc\x0e\xcc\x2d\x03\xdf\x78\xd4\x39\x00\xb4\x49\x7a\ -\xe3\xb0\x96\xe4\xc0\x1a\x30\xe8\xb0\x4a\x74\x03\x66\xb6\xe1\xb1\ -\xa7\x1c\x20\x3d\x84\x43\xc0\x9c\xc3\x0f\x63\x1b\x78\x0d\x0c\x00\ -\x7d\x0e\xdf\x49\x80\x8a\xa4\x0f\x81\x22\x03\x05\x0c\x9c\x03\x1f\ -\xcd\xec\x28\x0b\xde\x5e\xc3\x5f\x40\x28\x4c\x86\x0a\x18\xc8\x55\ -\x02\x5c\x99\xd9\xb1\x37\x40\x92\xfb\x5c\x93\x54\x02\x6a\xa4\x3f\ -\x91\xa5\x71\x60\x2f\xcf\x40\x11\x25\xa4\x61\xb3\xe4\xf0\x9e\x66\ -\x0a\x14\x91\x01\x17\x5e\x07\x25\x5d\xc4\x36\x90\xa7\x2a\xf0\x36\ -\x90\x03\x5f\x9a\x31\xd0\x09\x8c\x49\xca\x4a\xb4\x76\xa0\x2d\x30\ -\x77\x97\x74\x1b\xbc\x33\x72\xdd\x8c\x81\x13\xd2\xf7\xfd\x75\x06\ -\x4b\x80\x67\x81\xb9\x33\xc0\x28\xf0\xdb\xe1\x2b\x00\x65\x33\xe3\ -\x2e\x1f\x69\xd4\xae\x07\xf8\x32\x30\x19\xe0\xe5\x50\xfb\x5a\xa2\ -\xa2\x87\x50\xa4\x49\x5a\x73\xf8\x30\x91\x73\xa0\x01\x2c\x06\xf8\ -\x5c\x5e\x81\x42\x06\x2c\xdd\xc8\x50\x8a\x3e\x78\x0e\xf4\x03\xef\ -\x24\x4d\x38\xfc\x30\x01\x3a\x25\xc5\x32\x70\x00\xf4\xe2\x5f\xc3\ -\xd2\x3f\x6d\xfc\xb5\xcb\x34\x87\x52\x09\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x1d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x02\x9a\x49\x44\ -\x41\x54\x58\x85\xc5\x97\x3b\x4f\x54\x41\x14\x80\xbf\x03\x2b\xa8\ -\xab\x0b\xc6\xe7\x6a\x25\xd1\x46\xd6\x6c\x62\x67\xa3\x89\x0a\x58\ -\xf8\x2a\xac\xfc\x0f\xd6\xc4\xd2\xf8\x07\xfc\x13\x36\x42\x63\x69\ -\xa2\x95\x56\x6a\xc2\xae\xf2\xb0\x31\x11\x22\x16\x28\x9a\x98\xac\ -\x46\x03\x1e\x8b\x39\xc3\x0e\xc3\xdd\xbb\x73\x91\x64\x27\x99\x9c\ -\x99\x3b\x67\xce\x7c\x73\xce\x9d\x97\x00\x55\xa0\x45\x6f\x52\xb9\ -\x04\xb4\x54\xf5\x47\x2f\x46\x17\x11\xfa\x7a\x31\x70\x98\x7a\x0e\ -\x20\x40\x05\x18\x07\xf6\xd9\xb7\x19\x55\x6d\x6e\x51\x14\x19\x00\ -\xee\x58\xf5\x8d\xaa\xce\x8a\xc8\x38\x70\x1c\xf8\xae\xaa\x4f\x92\ -\x06\x14\x19\x01\x2e\x58\xf5\x19\x06\xf0\x11\x50\xcb\x4f\x55\x95\ -\x38\x03\xc3\x81\xce\xa4\x7d\x7b\x64\xf5\x4f\x59\x7d\x3a\xd8\xb9\ -\x1b\xd8\x39\x99\x15\x82\x4b\x22\x72\x30\x65\x36\xc0\xa2\xc9\xa3\ -\x22\x22\x89\x7d\xaa\x26\x7f\x02\xab\x59\x00\x25\xe0\x56\x41\x80\ -\x12\x70\x28\xb1\xcf\xb1\xb0\x6f\x0c\xa0\x26\x6f\x27\x1a\x5b\xca\ -\x30\x9c\x0a\xb0\x94\x05\xf0\xca\xe4\x65\x11\x39\x90\x60\x6c\x31\ -\x28\x57\x3b\x6a\x6d\x4e\x5e\x2f\xd3\x03\x0b\xc0\x2c\xb0\x8b\xb4\ -\x30\x84\x00\x45\x3d\x90\x09\x00\x30\x65\xb2\x6b\x18\x54\xb5\x05\ -\xac\xc6\x00\x22\x52\x17\x91\x86\xe5\x07\xc1\xf7\x3e\xe0\x70\x2a\ -\xc0\x98\x88\x0c\x77\x83\xa0\xed\x85\x30\x04\xe7\x80\xba\xe5\x89\ -\xe0\xfb\x11\xa0\x3f\x17\x40\x55\x17\x80\x39\x5c\x18\x6e\x16\x00\ -\x08\x43\x50\x0b\xca\xa3\x36\xf3\x58\xa7\xa3\x07\xa0\x40\x18\x68\ -\xaf\x84\xd0\x03\x1e\x60\x05\xd8\x0b\x8c\x44\x00\x6b\xc0\xe7\x3c\ -\x80\xc7\x26\xc7\x45\x64\xa8\x0b\x40\x96\x07\x46\x81\x3f\xc0\x74\ -\x04\xe4\x21\x97\x55\x75\xbd\x23\x40\x10\x86\x01\xe0\x46\x11\x00\ -\x5b\xbe\x27\x80\x79\xe0\xb5\xb5\x9d\x8d\x20\x37\x56\x4f\xde\x69\ -\x98\x1a\x06\x6f\x6c\x48\x44\xf6\xe0\x66\x0f\xd0\xb4\xfc\xdf\x00\ -\x13\x22\x52\x49\x00\xf0\x03\x78\x77\x37\x71\x5e\x58\xdb\x16\x80\ -\xaa\xce\x9b\x81\x41\xe0\x7a\x8e\xde\x57\xdc\xc1\xe2\x07\xf0\x1e\ -\x68\xa8\xea\x6f\xdc\xe6\x76\x5a\x44\x06\x89\x76\xc1\x5c\x00\x4b\ -\xa9\x61\x08\x57\x42\xe8\x01\x2f\xfb\x81\x33\x44\xe7\x40\x11\x80\ -\xab\xc0\xfe\x1c\xbd\xf0\x47\xac\xe1\xee\x07\xdf\x22\x90\x1a\x05\ -\xff\x01\x54\x75\x0e\xe7\xc2\xdd\xc0\xb5\x04\x80\x3a\xee\x58\x6e\ -\x04\x6d\xbe\x7c\x9e\xf6\x24\x92\x3d\x00\x69\x61\xf0\x00\x57\x4c\ -\x86\x57\x3a\x5f\x1e\x33\xb9\xa2\xaa\xbf\xb6\x03\x70\x31\x01\xc0\ -\xef\x78\x1b\x1e\x50\xd5\x2f\xb8\x5d\xef\x54\xa4\x9b\x06\xa0\xaa\ -\xb3\xc0\x7b\xda\x87\x48\x1e\x80\x4f\xf1\xa5\x36\xac\x17\x03\xb0\ -\x34\xd5\xa5\x3d\xbc\x19\xb5\x80\x0f\x39\x00\xa1\xee\x8e\x01\x2c\ -\xe3\x36\x1c\x80\xb7\xaa\xfa\x37\x6a\x0f\x7f\xca\x4d\x1e\x28\x99\ -\x7c\x88\xbb\x76\xcf\x64\x59\x57\xd5\x77\x22\x32\x89\x3b\xd9\x00\ -\x5e\x46\xed\xeb\x22\x72\x0f\xf7\xb6\xd8\xf2\xa6\x00\x5e\x00\xf7\ -\xad\xfc\x3c\x6c\x10\xa0\xd2\xc3\xb7\x61\xa5\xe7\x4f\xb3\x12\x50\ -\x4e\x7f\x53\xec\x78\x2a\xff\x03\x5a\xdd\xf8\xf7\x80\xbc\xec\x9a\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xc6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x01\x73\x52\x47\x42\x00\xae\xce\x1c\xe9\x00\x00\x00\ -\x06\x62\x4b\x47\x44\x00\xff\x00\xff\x00\xff\xa0\xbd\xa7\x93\x00\ -\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\x01\ -\x42\x28\x9b\x78\x00\x00\x00\x07\x74\x49\x4d\x45\x07\xdb\x03\x10\ -\x0f\x18\x06\xc3\xb0\x11\x52\x00\x00\x01\x46\x49\x44\x41\x54\x58\ -\xc3\xed\xd7\xc1\x2a\x05\x61\x14\x07\xf0\xdf\x70\x09\x57\x16\x58\ -\xb8\x58\xdc\x67\x90\x25\xa5\x2c\x3c\x80\xb5\xac\x65\x63\xe3\x05\ -\x3c\x80\x87\x50\xca\x8a\x2c\xa5\x2c\xb0\xf0\x04\xd6\x36\x22\x4a\ -\x11\x85\xba\x5d\x9b\x4f\xdd\xa6\x99\x3b\x83\xee\x8c\xb8\xa7\xbe\ -\xfe\x7d\xe7\xcc\x37\xe7\xdf\x77\xfe\x73\x4e\x13\xa1\x86\x17\xe5\ -\x58\xb5\x12\x92\x3f\x95\x44\x40\xa5\xa0\x3c\x2b\x58\x8f\xf9\x6e\ -\xb0\xda\x53\x10\x81\x05\xcc\xa0\x3f\x29\x38\x52\x00\x81\x0d\x34\ -\x51\x8f\xe7\xee\x51\xb2\x25\x11\x68\xc6\x56\x92\x4d\xe2\x0c\x6f\ -\x38\xc5\x44\x2c\xbe\x96\x71\x3e\x57\x09\xda\xbd\x60\x37\xc4\x96\ -\x03\xee\xb4\xc4\xea\xb8\x8f\x9d\x4f\x2d\xc1\x77\x09\x7c\x26\x18\ -\x0e\x78\x17\xfc\x11\x4e\xb0\x99\x97\xc0\x77\x35\x30\x1a\xf0\x25\ -\xb6\x5f\xc3\x10\xb6\x3b\xdd\x07\x1e\x30\x8e\x6a\xcb\x1e\xb6\x30\ -\x8f\xc6\x4f\x44\x28\x47\x49\x8e\x03\x2e\x05\x3c\x0a\x38\x86\xcb\ -\xbc\xe2\x4b\x13\x61\x33\x63\xc1\x14\xce\xf1\x1e\xbe\x86\x5a\x06\ -\xe1\x54\x0d\x24\x95\x20\xca\x41\xfa\x1a\x73\x19\xcf\x44\x5f\xd5\ -\x40\x1f\x7a\xcb\x98\x39\x9f\x25\xd8\xcb\x71\xfd\x3f\x5d\x6d\x4b\ -\x70\x88\xab\x0e\xdd\xc0\x2c\x16\xbf\xda\x09\xff\xef\x30\xea\x12\ -\xe8\x12\xe8\x12\xf8\x93\xff\x05\x03\x01\xa7\x5b\x7c\x0d\x3c\x16\ -\xd5\x09\x0f\x12\xe6\xc2\x6d\xda\x38\xee\x84\xed\x63\x10\x17\x78\ -\x0d\xbe\xe7\x22\x67\x41\xea\x1c\xfa\x15\x22\xac\x96\x98\xbf\xfa\ -\x01\x23\x9a\x68\x5e\xa9\x95\x69\x93\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x03\x63\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x10\x00\x00\x00\x13\x08\x06\x00\x00\x00\x99\x67\x8d\xcf\ -\x00\x00\x00\x04\x73\x42\x49\x54\x08\x08\x08\x08\x7c\x08\x64\x88\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0d\xd7\x00\x00\x0d\xd7\ -\x01\x42\x28\x9b\x78\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\ -\x74\x77\x61\x72\x65\x00\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x2e\x6f\x72\x67\x9b\xee\x3c\x1a\x00\x00\x02\xe0\x49\x44\ -\x41\x54\x38\x8d\x85\x93\x4d\x68\x5d\x55\x14\x85\xbf\xbd\xef\xcd\ -\x6b\x78\x49\x6c\x9b\xb4\xdc\xa3\xbc\xe6\x69\x05\x1b\x27\xa6\xa5\ -\x08\x1d\x28\x34\xa6\x54\xa4\x74\xaa\x86\x0e\x04\x27\x3a\x90\x20\ -\x8a\x9a\x3b\xf1\xb7\xe5\x0e\x2c\x2a\x62\x55\x4a\x07\x22\x98\x0a\ -\x1d\x88\x7f\x94\x52\x44\x45\x85\x82\x04\x07\xa2\xd5\x94\x5a\x6a\ -\x8d\x3d\x89\xa1\x16\xf3\xa3\x2f\xef\x9e\xb3\x1d\xf8\xae\x44\xeb\ -\xcf\x1e\x1d\x38\x6b\xad\xbd\xce\xd9\x6b\x8b\x99\xf1\x7f\xe5\x73\ -\xb7\x16\xd8\x0b\x6c\x03\x3e\x03\xde\x72\x85\x37\x80\xf4\x5f\x08\ -\x19\xb0\x15\xf8\x12\x58\x06\x9e\x00\x1a\xc0\x71\xe0\x6e\xe0\x4c\ -\xe7\xee\x4a\x01\x9f\x3b\x01\x26\x81\x12\x38\x0d\x4c\x03\x03\xc0\ -\x5d\x40\x0f\x70\x3b\xb0\xbe\xc2\xeb\xdf\xc8\x29\x70\x6f\x87\x7c\ -\x04\xd8\x02\x5c\x0f\x7c\xe2\x0a\x1f\xa3\xb1\xcb\xa2\x39\x11\x9e\ -\xf3\xb9\xeb\xb9\x42\x00\x78\x18\xd8\x0d\x8c\x03\x6b\x81\xcb\x1d\ -\x4c\x0f\x80\x24\xb6\x8c\x71\x34\x46\x33\x29\xad\xff\x2f\x02\x3e\ -\x77\x7d\x01\x6e\x03\xee\x71\x85\xff\x16\x98\xc4\x68\x00\x83\xc0\ -\x4d\x00\x57\x1f\x98\x3d\xa1\x35\xd9\x6c\xc2\x1a\x4b\x65\x01\x40\ -\x7d\xee\xea\x3e\x77\xe3\x26\xbc\x91\xc2\x86\xee\xa4\x95\x01\xb8\ -\xc2\x2f\x8b\xb0\xc6\xb0\x1d\x98\xd5\xaa\x46\xd9\x7e\xff\xa8\x22\ -\x6f\x57\xae\x14\x28\x80\xef\xd3\x5a\xdc\x57\x97\xe5\xdd\xeb\xf6\ -\xff\x7c\xbe\x02\x9b\xd9\x7b\x41\xe2\x58\x14\x8e\xce\x3c\xd2\x18\ -\xed\x38\xad\x01\xbf\x02\x57\x55\x53\x98\x01\x2e\x6c\x7c\x72\x6e\ -\x61\xf5\x67\x7c\xf4\x94\xa4\x43\xe9\xc0\xfb\x5d\x65\xba\x29\x98\ -\x2d\x24\x69\x7b\xd4\xe7\xae\x1b\xb8\x11\x98\x02\xbe\xa9\x1c\x3c\ -\x0b\x0c\xf9\xdc\x5d\xb3\x5a\x60\x27\xc4\x32\x74\xf5\x99\xda\x2e\ -\x55\xcd\x14\x19\x2d\x8d\x0c\x58\x72\x85\x3f\x51\x05\x49\x3b\x87\ -\x49\x60\xd8\xe7\xae\x0e\xf0\xdd\x83\xfd\xcd\xd9\x56\x76\xa0\x71\ -\xca\x7f\x2a\x51\x6e\x10\xb1\xa7\xa3\xd1\x14\xb5\x56\x88\x36\xe8\ -\x73\x37\xe2\x73\xd7\x04\x90\x2a\xca\x9d\xb7\x0d\x11\x93\x9d\x49\ -\x1a\xe7\x5b\x81\x6b\x7b\x5b\xdd\x2f\xb7\x7a\x7e\xd9\x42\xec\x7a\ -\x26\x46\x66\x52\x15\xdf\x0e\x71\x87\xaa\x7c\x1d\xc5\xa6\xd5\xe4\ -\xf8\xea\x1c\x34\xa2\x70\x9d\x24\x61\xd1\x44\xe6\xeb\xbf\xb5\x5e\ -\x5c\xf7\xfc\xb9\xcb\xb1\xdd\x35\x62\x51\xa6\x2c\xca\x87\x6d\x2b\ -\x3f\x4e\x14\x05\xc6\xc4\x64\x18\x18\x51\x80\x8b\x13\xd9\x04\x66\ -\xef\x60\xf6\x50\x30\x7b\x3c\x59\x91\x76\xff\x0b\x97\x16\x7d\xee\ -\xd6\x8b\x72\x04\xb1\x69\x49\xec\xd6\xde\xb0\x32\x55\x0a\xc7\x04\ -\x04\x64\x00\x68\x26\xf7\xb7\x5e\xed\x15\xe4\x10\xe8\xb8\x09\x0a\ -\xb2\x31\x28\x17\x96\x3e\x38\x58\x07\x6e\x01\xe6\x80\x2f\x14\xee\ -\x6c\x27\xb5\x9f\x42\xe4\x73\x11\xb6\x8b\x71\x12\xa1\x2f\x05\x06\ -\x45\xcc\x24\xb5\x73\x04\x1d\x16\xb1\x97\xb4\x5d\xce\x87\x24\x39\ -\x0f\x7c\xe5\x0a\x7f\x09\xe0\xc7\xc7\xb2\x77\x35\xb1\x07\x12\x4d\ -\x8f\xc5\x10\x5f\x13\xb1\xad\x0a\x67\x15\x98\x8b\x50\x2b\x83\xd5\ -\x16\x17\x7b\x0f\x65\x67\x66\xdf\x5c\x91\xf4\x0e\x60\xa1\x22\x03\ -\xa8\xca\xeb\x98\x9c\x52\x0b\xfb\x12\xb5\x31\x15\x96\x80\xc3\x72\ -\x71\x22\xeb\x06\x5e\xb1\x68\x37\x9b\xea\x61\x2c\x0c\xa9\x68\xd3\ -\x15\x7e\x0f\xff\x50\x9d\x75\x17\x57\xf8\xf8\xe7\x18\x7d\xee\x06\ -\xf8\x63\x13\x47\x80\x1f\x80\xfb\x56\x77\xff\xaf\xfa\x1d\xba\x24\ -\x3c\x2d\x28\xaa\x26\x54\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -" - -qt_resource_name = "\ -\x00\x09\ -\x07\x6f\x7f\x13\ -\x00\x65\ -\x00\x74\x00\x65\x00\x20\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x73\ -\x00\x0c\ -\x0b\xac\xc9\x87\ -\x00\x79\ -\x00\x5f\x00\x65\x00\x78\x00\x70\x00\x61\x00\x6e\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0c\ -\x05\x68\x0e\x67\ -\x00\x66\ -\x00\x69\x00\x6c\x00\x65\x00\x73\x00\x61\x00\x76\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0a\ -\x08\x94\x60\x47\ -\x00\x73\ -\x00\x65\x00\x61\x00\x72\x00\x63\x00\x68\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0e\ -\x0d\x20\x81\xa7\ -\x00\x73\ -\x00\x68\x00\x6f\x00\x77\x00\x5f\x00\x6e\x00\x61\x00\x6d\x00\x65\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0c\ -\x04\x7d\x40\x27\ -\x00\x79\ -\x00\x5f\x00\x72\x00\x65\x00\x64\x00\x75\x00\x63\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0c\ -\x08\x77\x3b\x27\ -\x00\x65\ -\x00\x74\x00\x65\x00\x5f\x00\x6c\x00\x6f\x00\x67\x00\x6f\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0c\ -\x05\x19\x1a\x27\ -\x00\x66\ -\x00\x69\x00\x74\x00\x5f\x00\x74\x00\x72\x00\x65\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0c\ -\x0b\x8c\xc9\x87\ -\x00\x78\ -\x00\x5f\x00\x65\x00\x78\x00\x70\x00\x61\x00\x6e\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0c\ -\x0b\x21\x0f\x87\ -\x00\x66\ -\x00\x69\x00\x6c\x00\x65\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0e\ -\x08\x44\x78\xa7\ -\x00\x65\ -\x00\x78\x00\x70\x00\x6f\x00\x72\x00\x74\x00\x5f\x00\x70\x00\x64\x00\x66\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x10\ -\x0c\x5c\xa4\x07\ -\x00\x73\ -\x00\x68\x00\x6f\x00\x77\x00\x5f\x00\x73\x00\x75\x00\x70\x00\x70\x00\x6f\x00\x72\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0c\ -\x06\xeb\x91\xa7\ -\x00\x7a\ -\x00\x6f\x00\x6f\x00\x6d\x00\x5f\x00\x6f\x00\x75\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0c\ -\x04\x5d\x40\x27\ -\x00\x78\ -\x00\x5f\x00\x72\x00\x65\x00\x64\x00\x75\x00\x63\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0b\ -\x05\x03\x9b\x27\ -\x00\x7a\ -\x00\x6f\x00\x6f\x00\x6d\x00\x5f\x00\x69\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0e\ -\x01\x2c\x5a\x47\ -\x00\x66\ -\x00\x69\x00\x74\x00\x5f\x00\x72\x00\x65\x00\x67\x00\x69\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x10\ -\x08\x0c\xea\xa7\ -\x00\x63\ -\x00\x6c\x00\x65\x00\x61\x00\x6e\x00\x5f\x00\x73\x00\x65\x00\x61\x00\x72\x00\x63\x00\x68\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0e\ -\x0b\x65\x21\x67\ -\x00\x66\ -\x00\x6f\x00\x72\x00\x63\x00\x65\x00\x5f\x00\x74\x00\x6f\x00\x70\x00\x6f\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x02\x33\x29\x27\ -\x00\x73\ -\x00\x68\x00\x6f\x00\x77\x00\x5f\x00\x6e\x00\x65\x00\x77\x00\x69\x00\x63\x00\x6b\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0d\ -\x03\x4a\xfd\xc7\ -\x00\x73\ -\x00\x68\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0c\ -\x07\xf4\x3c\xa7\ -\x00\x65\ -\x00\x74\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ -" - -qt_resource_struct = "\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x15\x00\x00\x00\x02\ -\x00\x00\x01\xc6\x00\x00\x00\x00\x00\x01\x00\x00\x50\xd4\ -\x00\x00\x02\x30\x00\x00\x00\x00\x00\x01\x00\x00\x5e\x6f\ -\x00\x00\x02\x54\x00\x00\x00\x00\x00\x01\x00\x00\x61\x90\ -\x00\x00\x01\x8c\x00\x00\x00\x00\x00\x01\x00\x00\x48\x30\ -\x00\x00\x00\x90\x00\x00\x00\x00\x00\x01\x00\x00\x0e\x97\ -\x00\x00\x01\xaa\x00\x00\x00\x00\x00\x01\x00\x00\x4b\xcc\ -\x00\x00\x00\xcc\x00\x00\x00\x00\x00\x01\x00\x00\x2e\x72\ -\x00\x00\x00\xcc\x00\x00\x00\x00\x00\x01\x00\x00\x28\x92\ -\x00\x00\x00\x36\x00\x00\x00\x00\x00\x01\x00\x00\x03\x4a\ -\x00\x00\x01\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x43\x53\ -\x00\x00\x02\x74\x00\x00\x00\x00\x00\x01\x00\x00\x63\x5a\ -\x00\x00\x01\xe8\x00\x00\x00\x00\x00\x01\x00\x00\x55\x10\ -\x00\x00\x01\x26\x00\x00\x00\x00\x00\x01\x00\x00\x3b\xa4\ -\x00\x00\x00\xae\x00\x00\x00\x00\x00\x01\x00\x00\x12\x12\ -\x00\x00\x00\x54\x00\x00\x00\x00\x00\x01\x00\x00\x06\x3d\ -\x00\x00\x01\x08\x00\x00\x00\x00\x00\x01\x00\x00\x37\xde\ -\x00\x00\x02\x0e\x00\x00\x00\x00\x00\x01\x00\x00\x5c\x24\ -\x00\x00\x00\xea\x00\x00\x00\x00\x00\x01\x00\x00\x34\x52\ -\x00\x00\x00\x18\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\ -\x00\x00\x01\x48\x00\x00\x00\x00\x00\x01\x00\x00\x40\xc4\ -\x00\x00\x00\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x0c\xa8\ -" - -def qInitResources(): - QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) - -def qCleanupResources(): - QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) - -qInitResources() diff --git a/ete2/treeview/ete_resources_rc.pyc b/ete2/treeview/ete_resources_rc.pyc deleted file mode 100644 index d52eea4..0000000 Binary files a/ete2/treeview/ete_resources_rc.pyc and /dev/null differ diff --git a/ete2/treeview/faces.py b/ete2/treeview/faces.py deleted file mode 100644 index 8ecbab2..0000000 --- a/ete2/treeview/faces.py +++ /dev/null @@ -1,2026 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -#START_LICENSE########################################################### -#END_LICENSE############################################################# - -from PyQt4.QtGui import (QGraphicsRectItem, QGraphicsLineItem, - QGraphicsPolygonItem, QGraphicsEllipseItem, - QPen, QColor, QBrush, QPolygonF, QFont, - QPixmap, QFontMetrics, QPainter, - QRadialGradient, QGraphicsSimpleTextItem, - QGraphicsItem) -from PyQt4.QtCore import Qt, QPointF, QRect, QRectF - -from numpy import isfinite as _isfinite, ceil -import math -from main import add_face_to_node, _Background, _Border, COLOR_SCHEMES - -isfinite = lambda n: n and _isfinite(n) - -_aafgcolors = { - 'A':"#000000" , - 'R':"#000000" , - 'N':"#000000" , - 'D':"#000000" , - 'C':"#000000" , - 'Q':"#000000" , - 'E':"#000000" , - 'G':"#000000" , - 'H':"#000000" , - 'I':"#000000" , - 'L':"#000000" , - 'K':"#000000" , - 'M':"#000000" , - 'F':"#000000" , - 'P':"#000000" , - 'S':"#000000" , - 'T':"#000000" , - 'W':"#000000" , - 'Y':"#000000" , - 'V':"#000000" , - 'B':"#000000" , - 'Z':"#000000" , - 'X':"#000000", - '.':"#000000", - '-':"#000000", -} - -_aabgcolors = { - 'A':"#C8C8C8" , - 'R':"#145AFF" , - 'N':"#00DCDC" , - 'D':"#E60A0A" , - 'C':"#E6E600" , - 'Q':"#00DCDC" , - 'E':"#E60A0A" , - 'G':"#EBEBEB" , - 'H':"#8282D2" , - 'I':"#0F820F" , - 'L':"#0F820F" , - 'K':"#145AFF" , - 'M':"#E6E600" , - 'F':"#3232AA" , - 'P':"#DC9682" , - 'S':"#FA9600" , - 'T':"#FA9600" , - 'W':"#B45AB4" , - 'Y':"#3232AA" , - 'V':"#0F820F" , - 'B':"#FF69B4" , - 'Z':"#FF69B4" , - 'X':"#BEA06E", - '.':"#FFFFFF", - '-':"#FFFFFF", - } - -_ntfgcolors = { - 'A':'#000000', - 'G':'#000000', - 'I':'#000000', - 'C':'#000000', - 'T':'#000000', - 'U':'#000000', - '.':"#000000", - '-':"#000000", - ' ':"#000000" - } - -_ntbgcolors = { - 'A':'#A0A0FF', - 'G':'#FF7070', - 'I':'#80FFFF', - 'C':'#FF8C4B', - 'T':'#A0FFA0', - 'U':'#FF8080', - '.':"#FFFFFF", - '-':"#FFFFFF", - ' ':"#FFFFFF" -} - -__all__ = ["Face", "TextFace", "AttrFace", "ImgFace", - "ProfileFace", "SequenceFace", "TreeFace", - "RandomFace", "DynamicItemFace", "StaticItemFace", - "CircleFace", "PieChartFace", "BarChartFace", "SeqMotifFace"] - -class Face(object): - """Base Face object. All Face types (i.e. TextFace, SeqMotifFace, - etc.) inherit the following options: - - :param 0 margin_left: in pixels - :param 0 margin_right: in pixels - :param 0 margin_top: in pixels - :param 0 margin_bottom: in pixels - :param 1.0 opacity: a float number in the (0,1) range - :param True rotable: If True, face will be rotated when necessary - (i.e. when circular mode is enabled and face occupies an inverted position.) - :param 0 hz_align: 0 left, 1 center, 2 right - :param 1 vt_align: 0 top, 1 center, 2 bottom - :param background.color: background color of face plus all its margins. - :param inner_background.color: background color of the face excluding margins - :param border: Border around face margins. - :param inner_border: Border around face excluding margins. - - **border and inner_border sub-parameters:** - - :param 0 (inner\_)border.type: 0=solid, 1=dashed, 2=dotted - :param None (inner\_)border.width: a positive integer number. Zero - indicates a cosmetic pen. This means that - the pen width is always drawn one pixel - wide, independent of the transformation - set on the painter. A "None" value means - invisible border. - :param black (inner\_)border.color: RGB or color name in :data:`SVG_COLORS` - - See also specific options for each face type. - - """ - - def __init__(self): - self.node = None - self.type = "pixmap" # pixmap, text or item - - self.margin_left = 0 - self.margin_right = 0 - self.margin_top = 0 - self.margin_bottom = 0 - self.pixmap = None - self.opacity = 1.0 - self.rotable = True - self.hz_align = 0 # 0 left, 1 center, 2 right - self.vt_align = 1 - self.background = _Background() - self.border = _Border() - self.inner_border = _Border() - self.inner_background = _Background() - self.rotation = 0 - - def _size(self): - if self.pixmap: - return self._width(),self._height() - else: - return 0, 0 - - def _width(self): - if self.pixmap: - return self.pixmap.width() - else: - return 0 - - def _height(self): - if self.pixmap: - return self.pixmap.height() - else: - return 0 - - def load_pixmap_from_file(self, filename): - self.pixmap = QPixmap(filename) - - def update_pixmap(self): - pass - - -class TextFace(Face): - """Static text Face object - - .. currentmodule:: ete2 - - :param text: Text to be drawn - :param ftype: Font type, e.g. Arial, Verdana, Courier - :param fsize: Font size, e.g. 10,12,6, (default=10) - :param fgcolor: Foreground font color. RGB code or color name in :data:`SVG_COLORS` - :param penwidth: Penwdith used to draw the text. - :param fstyle: "normal" or "italic" - - :param True tight_text: When False, boundaries of the text are - approximated according to general font metrics, producing slightly - worse aligned text faces but improving the performance of tree - visualization in scenes with a lot of text faces. - """ - - def __repr__(self): - return "Text Face [%s] (%s)" %(self._text, hex(self.__hash__())) - - def _load_bounding_rect(self, txt=None): - if txt is None: - txt= self.get_text() - fm = QFontMetrics(self._get_font()) - tx_w = fm.width(txt) - if self.tight_text: - textr = fm.tightBoundingRect(self.get_text()) - down = textr.height() + textr.y() - up = textr.height() - down - asc = fm.ascent() - des = fm.descent() - center = (asc + des) / 2.0 - xcenter = ((up+down)/2.0) + asc - up - self._bounding_rect = QRectF(0, asc - up, tx_w, textr.height()) - self._real_rect = QRectF(0, 0, tx_w, textr.height()) - else: - textr = fm.boundingRect(txt) - self._bounding_rect = QRectF(0, 0, tx_w, textr.height()) - self._real_rect = QRectF(0, 0, tx_w, textr.height()) - - def _get_text(self): - return self._text - - def _set_text(self, txt): - self._text = str(txt) - - def get_bounding_rect(self): - if not self._bounding_rect: - self._load_bounding_rect() - return self._bounding_rect - - def get_real_rect(self): - if not self._real_rect: - self._load_bounding_rect() - return self._bounding_rect - - text = property(_get_text, _set_text) - def __init__(self, text, ftype="Verdana", fsize=10, - fgcolor="black", penwidth=0, fstyle="normal", - tight_text=True): - self._text = str(text) - self._bounding_rect = None - self._real_rect = None - - Face.__init__(self) - self.pixmap = None - self.type = "text" - self.fgcolor = fgcolor - self.ftype = ftype - self.fsize = fsize - self.fstyle = fstyle - self.penwidth = penwidth - self.tight_text = tight_text - - def _get_font(self): - font = QFont(self.ftype, self.fsize) - if self.fstyle == "italic": - font.setStyle(QFont.StyleItalic) - elif self.fstyle == "oblique": - font.setStyle(QFont.StyleOblique) - return font - - def _height(self): - return self.get_bounding_rect().height() - - def _width(self): - return self.get_bounding_rect().width() - - def get_text(self): - return self._text - -class AttrFace(TextFace): - """ - - Dynamic text Face. Text rendered is taken from the value of a - given node attribute. - - :param attr: Node's attribute that will be drawn as text - :param ftype: Font type, e.g. Arial, Verdana, Courier, (default="Verdana") - :param fsize: Font size, e.g. 10,12,6, (default=10) - :param fgcolor: Foreground font color. RGB code or name in :data:`SVG_COLORS` - :param penwidth: Penwdith used to draw the text. (default is 0) - :param text_prefix: text_rendered before attribute value - :param text_suffix: text_rendered after attribute value - :param formatter: a text string defining a python formater to - process the attribute value before renderer. e.g. "%0.2f" - :param fstyle: "normal" or "italic" - """ - - def __repr__(self): - return "Attribute Face [%s] (%s)" %(self.attr, hex(self.__hash__())) - - def get_text(self): - if self.attr_formatter: - text = self.attr_formatter % getattr(self.node, self.attr) - else: - text = str(getattr(self.node, self.attr)) - text = ''.join(map(str, [self.text_prefix, \ - text, \ - self.text_suffix])) - return text - - def get_bounding_rect(self): - current_text = self.get_text() - if current_text != self._bounding_rect_text: - self._load_bounding_rect(current_text) - self._bounding_rect_text = current_text - return self._bounding_rect - - def get_real_rect(self): - current_text = self.get_text() - if current_text != self._bounding_rect_text: - self._load_bounding_rect(current_text) - self._bounding_rect_text = current_text - return self._real_rect - - def __init__(self, attr, ftype="Verdana", fsize=10, - fgcolor="black", penwidth=0, text_prefix="", - text_suffix="", formatter=None, fstyle="normal", - tight_text=True): - - Face.__init__(self) - TextFace.__init__(self, None, ftype, fsize, fgcolor, penwidth, - fstyle, tight_text) - self.attr = attr - self.type = "text" - self.text_prefix = text_prefix - self.text_suffix = text_suffix - self.attr_formatter = formatter - self._bounding_rect_text = "" - -class ImgFace(Face): - """Creates a node Face using an external image file. - - :param img_file: path to the image file. - :param None width: if provided, image will be scaled to this width (in pixels) - :param None height: if provided, image will be scaled to this height (in pixels) - - If only one dimension value (width or height) is provided, the other - will be calculated to keep aspect ratio. - - """ - - def __init__(self, img_file, width=None, height=None): - Face.__init__(self) - self.img_file = img_file - self.width = width - self.height = height - - def update_pixmap(self): - self.pixmap = QPixmap(self.img_file)# flags=Qt.DiffuseAlphaDither) - - if self.width or self.height: - w, h = self.width, self.height - ratio = self.pixmap.width() / float(self.pixmap.height()) - if not w: - w = ratio * h - if not h: - h = w / ratio - self.pixmap = self.pixmap.scaled(w, h) - -class ProfileFace(Face): - """ - A profile Face for ClusterNodes - - :param max_v: maximum value used to build the build the plot scale. - :param max_v: minimum value used to build the build the plot scale. - :param center_v: Center value used to scale plot and heatmap. - :param 200 width: Plot width in pixels. - :param 40 height: Plot width in pixels. - :param lines style: Plot style: "lines", "bars", "cbars" or "heatmap". - - :param 2 colorscheme: colors used to create the gradient from - min values to max values. 0=green & blue; 1=green & red; 2=red & - blue. In all three cases, missing values are rendered in black - and transition color (values=center) is white. - """ - - def __init__(self,max_v,min_v,center_v,width=200,height=40,style="lines", colorscheme=2): - Face.__init__(self) - - self.width = width - self.height = height - self.max_value = max_v - self.min_value = min_v - self.center_v = center_v - self.style = style - self.colorscheme = colorscheme - - def update_pixmap(self): - if self.style=="lines": - self.draw_line_profile() - elif self.style=="heatmap": - self.draw_heatmap_profile() - elif self.style=="bars": - self.draw_bar_profile() - elif self.style=="cbars": - self.draw_centered_bar_profile() - - def get_color_gradient(self): - colors = [] - if self.colorscheme == 0: - # Blue and Green - for a in xrange(100,0,-1): - color=QColor() - color.setRgb( 200-2*a,255,200-2*a ) - colors.append(color) - - colors.append(QColor("white")) - - for a in xrange(0,100): - color=QColor() - color.setRgb( 200-2*a,200-2*a,255 ) - colors.append(color) -# color=QColor() -# color.setRgb( 0,255,255 ) -# colors.append(color) - - elif self.colorscheme == 1: - for a in xrange(100,0,-1): - color=QColor() - color.setRgb( 200-2*a,255,200-2*a ) - colors.append(color) - - colors.append(QColor("white")) - - for a in xrange(0,100): - color=QColor() - color.setRgb( 255,200-2*a,200-2*a ) - colors.append(color) -# color=QColor() -# color.setRgb(255,255,0 ) -# colors.append(color) - - else: - # Blue and Red - for a in xrange(100,0,-1): - color=QColor() - color.setRgb( 200-2*a,200-2*a,255 ) - colors.append(color) - - colors.append(QColor("white")) - - for a in xrange(0,100): - color=QColor() - color.setRgb( 255,200-2*a,200-2*a ) - colors.append(color) - -# color=QColor() -# color.setRgb( 255,0,255 ) -# colors.append(color) - - return colors - - def draw_bar_profile(self): - # Calculate vector - mean_vector = self.node.profile - deviation_vector = self.node.deviation - # If no vector, skip - if mean_vector is None: - return - - colors = self.get_color_gradient() - - vlength = len(mean_vector) - # pixels per array position - profile_width = self.width - 40 - profile_height= self.height - - x_alpha = float( profile_width / (len(mean_vector)) ) - y_alpha = float ( (profile_height-1) / (self.max_value-self.min_value) ) - - # Creates a pixmap - self.pixmap = QPixmap(self.width,self.height) - self.pixmap.fill(QColor("white")) - p = QPainter(self.pixmap) - - x2 = 0 - y = 0 - - # Mean and quartiles y positions - mean_line_y = y + profile_height/2 - line2_y = mean_line_y + profile_height/4 - line3_y = mean_line_y - profile_height/4 - - # Draw axis and scale - p.setPen(QColor("black")) - p.drawRect(x2,y,profile_width, profile_height-1) - p.setFont(QFont("Verdana",8)) - p.drawText(profile_width,y+10,"%0.3f" %self.max_value) - p.drawText(profile_width,y+profile_height,"%0.3f" %self.min_value) - - dashedPen = QPen(QBrush(QColor("#ddd")), 0) - dashedPen.setStyle(Qt.DashLine) - - # Draw hz grid - p.setPen(dashedPen) - p.drawLine(x2+1, mean_line_y, profile_width-2, mean_line_y ) - p.drawLine(x2+1, line2_y, profile_width-2, line2_y ) - p.drawLine(x2+1, line3_y, profile_width-2, line3_y ) - - - # Draw bars - for pos in xrange(vlength): - # first and second X pixel positions - x1 = x2 - x2 = x1 + x_alpha - - dev1 = self.fit_to_scale(deviation_vector[pos]) - mean1 = self.fit_to_scale(mean_vector[pos]) - - # If nan value, skip - if not isfinite(mean1): - continue - - # Set heatmap color - if mean1 > self.center_v: - color_index = abs(int(ceil(((self.center_v - mean1) * 100) / (self.max_value - self.center_v)))) - customColor = colors[100 + color_index] - elif mean1 < self.center_v: - color_index = abs(int(ceil(((self.center_v - mean1) * 100) / (self.min_value - self.center_v)))) - customColor = colors[100 - color_index] - else: - customColor = colors[100] - - # mean bar high - mean_y1 = int ( (mean1 - self.min_value) * y_alpha) - - # Draw bar border - p.setPen(QColor("black")) - #p.drawRect(x1+2,mean_y1, x_alpha-3, profile_height-mean_y1+1) - # Fill bar with custom color - p.fillRect(x1+3,profile_height-mean_y1, x_alpha-4, mean_y1-1, QBrush(customColor)) - - # Draw error bars - if dev1 != 0: - dev_up_y1 = int((mean1+dev1 - self.min_value) * y_alpha) - dev_down_y1 = int((mean1-dev1 - self.min_value) * y_alpha) - p.drawLine(x1+x_alpha/2, profile_height-dev_up_y1 ,x1+x_alpha/2, profile_height-dev_down_y1 ) - p.drawLine(x1-1+x_alpha/2, profile_height-dev_up_y1, x1+1+x_alpha/2, profile_height-dev_up_y1 ) - p.drawLine(x1-1+x_alpha/2, profile_height-dev_down_y1, x1+1+x_alpha/2, profile_height-dev_down_y1 ) - - def draw_centered_bar_profile(self): - # Calculate vector - mean_vector = self.node.profile - deviation_vector = self.node.deviation - # If no vector, skip - if mean_vector is None: - return - - colors = self.get_color_gradient() - - vlength = len(mean_vector) - # pixels per array position - profile_width = self.width - 40 - profile_height= self.height - - x_alpha = float( profile_width / (len(mean_vector)) ) - y_alpha_up = float ( ((profile_height-1)/2) / (self.max_value-self.center_v) ) - y_alpha_down = float ( ((profile_height-1)/2) / (self.min_value-self.center_v) ) - - # Creates a pixmap - self.pixmap = QPixmap(self.width,self.height) - self.pixmap.fill(QColor("white")) - p = QPainter(self.pixmap) - - x2 = 0 - y = 0 - - # Mean and quartiles y positions - mean_line_y = y + profile_height/2 - line2_y = mean_line_y + profile_height/4 - line3_y = mean_line_y - profile_height/4 - - # Draw axis and scale - p.setPen(QColor("black")) - p.drawRect(x2,y,profile_width, profile_height-1) - p.setFont(QFont("Verdana",8)) - p.drawText(profile_width,y+10,"%0.3f" %self.max_value) - p.drawText(profile_width,y+profile_height,"%0.3f" %self.min_value) - p.drawText(profile_width,mean_line_y,"%0.3f" %self.center_v) - - dashedPen = QPen(QBrush(QColor("#ddd")), 0) - dashedPen.setStyle(Qt.DashLine) - - # Draw hz grid - p.setPen(dashedPen) - p.drawLine(x2+1, mean_line_y, profile_width-2, mean_line_y ) - p.drawLine(x2+1, line2_y, profile_width-2, line2_y ) - p.drawLine(x2+1, line3_y, profile_width-2, line3_y ) - - - # Draw bars - for pos in xrange(vlength): - # first and second X pixel positions - x1 = x2 - x2 = x1 + x_alpha - - dev1 = self.fit_to_scale( deviation_vector[pos] ) - mean1 = self.fit_to_scale( mean_vector[pos] ) - - # If nan value, skip - if not isfinite(mean1): - continue - - # Set heatmap color - if mean1>self.center_v: - color_index = abs(int(ceil(((self.center_v-mean1)*100)/(self.max_value-self.center_v)))) - customColor = colors[100 + color_index] - - #print mean1, color_index, len(colors), "%x" %colors[100 + color_index].rgb() - #print abs(((self.center_v-mean1)*100)/(self.max_value-self.center_v)) - #print round(((self.center_v-mean1)*100)/(self.max_value-self.center_v)) - - elif mean1self.center_v: - color_index = abs(int(ceil(((self.center_v-mean1)*100)/(self.max_value-self.center_v)))) - customColor = colors[100 + color_index] - elif mean1self.max_value: - return float(self.max_value) - else: - return float(v) - - -class OLD_SequenceFace(Face): - """ Creates a new molecular sequence face object. - - - :param seq: Sequence string to be drawn - :param seqtype: Type of sequence: "nt" or "aa" - :param fsize: Font size, (default=10) - - You can set custom colors for aminoacids or nucleotides: - - :param aafg: a dictionary in which keys are aa codes and values - are foreground RGB colors - - :param aabg: a dictionary in which keys are aa codes and values - are background RGB colors - - :param ntfg: a dictionary in which keys are nucleotides codes - and values are foreground RGB colors - - :param ntbg: a dictionary in which keys are nucleotides codes and values - are background RGB colors - - """ - - def __init__(self, seq, seqtype, fsize=10, aafg=None, \ - aabg=None, ntfg=None, ntbg=None): - - Face.__init__(self) - self.seq = seq - self.fsize= fsize - self.fsize = fsize - self.style = seqtype - - if not aafg: - aafg = _aafgcolors - if not aabg: - aabg = _aabgcolors - if not ntfg: - ntfg = _ntfgcolors - if not ntbg: - ntbg = _ntbgcolors - - self.aafg = aafg - self.aabg = aabg - self.ntfg = ntfg - self.ntbg = ntbg - - def update_pixmap(self): - font = QFont("Courier", self.fsize) - fm = QFontMetrics(font) - height = fm.leading() + fm.overlinePos() + fm.underlinePos() - #width = fm.size(Qt.AlignTop, self.seq).width() - width = self.fsize * len(self.seq) - - self.pixmap = QPixmap(width,height) - self.pixmap.fill() - p = QPainter(self.pixmap) - x = 0 - y = height - fm.underlinePos()*2 - - p.setFont(font) - - for letter in self.seq: - letter = letter.upper() - - if self.style=="nt": - letter_brush = QBrush(QColor(self.ntbg.get(letter,"white" ))) - letter_pen = QPen(QColor(self.ntfg.get(letter, "black"))) - else: - letter_brush = QBrush(QColor(self.aabg.get(letter,"white" ))) - letter_pen = QPen(QColor(self.aafg.get(letter,"black" ))) - - p.setPen(letter_pen) - p.fillRect(x,0,width, height,letter_brush) - p.drawText(x, y, letter) - x += float(width)/len(self.seq) - p.end() - -class TreeFace(Face): - """ - .. versionadded:: 2.1 - - Creates a Face containing a Tree object. Yes, a tree within a tree :) - - :param tree: An ETE Tree instance (Tree, PhyloTree, etc...) - :param tree_style: A TreeStyle instance defining how tree show be drawn - - """ - def __init__(self, tree, tree_style): - Face.__init__(self) - self.type = "item" - self.root_node = tree - self.img = tree_style - self.item = None - - def update_items(self): - from qt4_render import render, init_tree_style - ts = init_tree_style(self.root_node, self.img) - hide_root = False - if self.root_node is self.node: - hide_root = True - self.item, self.n2i, self.n2f = render(self.root_node, ts, hide_root) - - def _width(self): - return self.item.rect().width() - - def _height(self): - return self.item.rect().height() - - -class _SphereItem(QGraphicsEllipseItem): - def __init__(self, radius, color, solid=False): - r = radius - d = r*2 - QGraphicsEllipseItem.__init__(self, 0, 0, d, d) - self.gradient = QRadialGradient(r, r, r,(d)/3,(d)/3) - self.gradient.setColorAt(0.05, Qt.white) - self.gradient.setColorAt(1, QColor(color)) - if solid: - self.setBrush(QBrush(QColor(color))) - else: - self.setBrush(QBrush(self.gradient)) - self.setPen(QPen(QColor(color))) - #self.setPen(Qt.NoPen) - -class CircleFace(Face): - """ - .. versionadded:: 2.1 - - Creates a Circle or Sphere Face. - - :param radius: integer number defining the radius of the face - :param color: Color used to fill the circle. RGB code or name in :data:`SVG_COLORS` - :param "circle" style: Valid values are "circle" or "sphere" - """ - - def __init__(self, radius, color, style="circle"): - Face.__init__(self) - self.radius = radius - self.style = style - self.color = color - self.type = "item" - self.rotable = False - - def update_items(self): - if self.style == "circle": - self.item = _SphereItem(self.radius, self.color, solid=True) - elif self.style == "sphere": - self.item = _SphereItem(self.radius, self.color) - - def _width(self): - return self.item.rect().width() - - def _height(self): - return self.item.rect().height() - - -class StaticItemFace(Face): - """ - .. versionadded:: 2.1 - - Creates a face based on an external QtGraphicsItem object. - QGraphicsItem object is expected to be independent from tree node - properties, so its content is assumed to be static (drawn only - once, no updates when tree changes). - - :param item: an object based on QGraphicsItem - """ - def __init__(self, item): - Face.__init__(self) - self.type = "item" - self.item = item - - def update_items(self): - return - - def _width(self): - return self.item.rect().width() - - def _height(self): - return self.item.rect().height() - - -class DynamicItemFace(Face): - """ - .. versionadded:: 2.1 - - Creates a face based on an external QGraphicsItem object whose - content depends on the node that is linked to. - - :param constructor: A pointer to a method (function or class - constructor) returning a QGraphicsItem based - object. "constructor" method is expected to receive a node - instance as the first argument. The rest of arguments passed to - ItemFace are optional and will passed also to the constructor - function. - """ - - def __init__(self, constructor, *args, **kargs): - Face.__init__(self) - self.type = "item" - self.item = None - self.constructor = constructor - self.args = args - self.kargs = kargs - - def update_items(self): - self.item = self.constructor(self.node, self.args, self.kargs) - - def _width(self): - return self.item.rect().width() - - def _height(self): - return self.item.rect().height() - - -class RandomFace(Face): - def __init__(self): - Face.__init__(self) - self.type = "item" - - def update_items(self): - import random - w = random.randint(4, 100) - h = random.randint(4, 100) - self.tree_partition = QGraphicsRectItem(0,0,w, h) - self.tree_partition.setBrush(QBrush(QColor("green"))) - - def _width(self): - return self.tree_partition.rect().width() - - def _height(self): - return self.tree_partition.rect().height() - -class _PieChartItem(QGraphicsRectItem): - def __init__(self, percents, width, height, colors, line_color=None): - QGraphicsRectItem.__init__(self, 0, 0, width, height) - self.percents = percents - self.colors = colors - self.line_color = line_color - - def paint(self, painter, option, widget): - a = 5760 - angle_start = 0 - - if not self.line_color: - painter.setPen(Qt.NoPen) - else: - painter.setPen(QColor(self.line_color)) - - for i, p in enumerate(self.percents): - col = self.colors[i] - painter.setBrush(QBrush(QColor(col))) - angle_span = (p/100.) * a - painter.drawPie(self.rect(), angle_start, angle_span ) - angle_start += angle_span - - -class PieChartFace(StaticItemFace): - """ - .. versionadded:: 2.2 - - :param percents: a list of values summing up 100. - :param width: width of the piechart - :param height: height of the piechart - :param colors: a list of colors (same length as percents) - - """ - def __init__(self, percents, width, height, colors=None, line_color=None): - Face.__init__(self) - - if round(sum(percents)) > 100: - raise ValueError("PieChartItem: percentage values > 100") - - self.type = "item" - self.item = None - self.percents = percents - if not colors: - colors = COLOR_SCHEMES["paired"] - self.colors = colors - self.width = width - self.height = height - self.line_color = line_color - - def update_items(self): - self.item = _PieChartItem(self.percents, self.width, - self.height, self.colors, self.line_color) - - def _width(self): - return self.item.rect().width() - - def _height(self): - return self.item.rect().height() - - -class BarChartFace(Face): - """ - .. versionadded:: 2.2 - - :param percents: a list of values summing up 100. - :param width: width of the piechart - :param height: height of the piechart - :param colors: a list of colors (same length as percents) - - """ - def __init__(self, values, deviations=None, width=200, height=100, colors=None, labels=None, min_value=0, max_value=None): - Face.__init__(self) - self.type = "item" - self.item = None - self.values = values - if not deviations: - self.deviations = [0] * len(values) - else: - self.deviations = deviations - - if not colors: - colors = COLOR_SCHEMES["paired"] - self.colors = colors - - - self.width = width - self.height = height - self.labels = labels - self.max_value = max_value - self.min_value = min_value - self.margin_left = 1 - self.margin_right = 1 - self.margin_top = 2 - self.margin_bottom = 2 - - def update_items(self): - self.item = _BarChartItem(self.values, self.deviations, self.width, - self.height, self.colors, self.labels, - self.min_value, self.max_value) - - def _width(self): - return self.item.rect().width() - - def _height(self): - return self.item.rect().height() - - -class _BarChartItem(QGraphicsRectItem): - def __init__(self, values, deviations, width, height, colors, labels, min_value, max_value): - QGraphicsRectItem.__init__(self, 0, 0, width, height) - self.values = values - self.colors = colors - self.width = width - self.height = height - self.draw_border = True - self.draw_grid = False - self.draw_scale = True - self.labels = labels - self.max_value = max_value - self.min_value = min_value - self.deviations = deviations - - def paint(self, p, option, widget): - colors = self.colors - values = self.values - deviations = self.deviations - p.setBrush(Qt.NoBrush) - - spacer = 3 - spacing_length = (spacer*(len(values)-1)) - height = self.height - - if self.max_value is None: - max_value = max([v+d for v,d in zip(values, deviations) if isfinite(v)]) - else: - max_value = self.max_value - - if self.min_value is None: - min_value = min([v+d for v,d in zip(values, deviations) if isfinite(v)]) - else: - min_value = 0 - - scale_length = 0 - scale_margin = 2 - if self.draw_scale: - p.setFont(QFont("Verdana", 6)) - max_string = "% 7.2f" %max_value - min_string = "% 7.2f" %min_value - fm = QFontMetrics(p.font()) - max_string_metrics = fm.boundingRect(QRect(), \ - Qt.AlignLeft, \ - max_string) - min_string_metrics = fm.boundingRect(QRect(), \ - Qt.AlignLeft, \ - min_string) - scale_length = scale_margin + max(max_string_metrics.width(), - min_string_metrics.width()) - - - label_height = 0 - if self.labels: - p.setFont(QFont("Verdana", 6)) - fm = QFontMetrics(p.font()) - longest_label = sorted(self.labels, lambda x,y: cmp(len(x), len(y)))[-1] - label_height = fm.boundingRect(QRect(), Qt.AlignLeft, longest_label).width() - - - real_width = self.width - scale_length - x_alpha = float((real_width - spacing_length) / (len(values))) - if x_alpha < 1: - raise ValueError("BarChartFace is too small") - - full_height = height - height -= label_height - y_alpha = float ( (height-1) / float(max_value - min_value) ) - x = 0 - y = 0 - - # Mean and quartiles y positions - mean_line_y = y + height / 2 - line2_y = mean_line_y + height/4 - line3_y = mean_line_y - height/4 - - if self.draw_border: - p.setPen(QColor("black")) - p.drawRect(x, y, real_width + scale_margin - 1 , height) - - if self.draw_scale: - p.drawText(real_width + scale_margin, max_string_metrics.height(), max_string) - p.drawText(real_width + scale_margin, height - 2, min_string) - p.drawLine(real_width + scale_margin - 1, 0, real_width + scale_margin - 1, height) - p.drawLine(real_width + scale_margin - 1, 0, real_width + scale_margin + 2, y) - p.drawLine(real_width + scale_margin - 1, height, real_width + scale_margin + 2, height) - - if self.draw_grid: - dashedPen = QPen(QBrush(QColor("#ddd")), 0) - dashedPen.setStyle(Qt.DashLine) - p.setPen(dashedPen) - p.drawLine(x+1, mean_line_y, real_width - 2, mean_line_y ) - p.drawLine(x+1, line2_y, real_width - 2, line2_y ) - p.drawLine(x+1, line3_y, real_width - 2, line3_y ) - - # Draw bars - for pos in xrange(len(values)): - # first and second X pixel positions - x1 = x - x = x1 + x_alpha + spacer - - std = deviations[pos] - val = values[pos] - - if self.labels: - p.save() - p.translate(x1, height) - p.rotate(90) - p.drawText(0, 0, str(self.labels[pos])) - p.restore() - - # If nan value, skip - if not isfinite(val): - continue - - color = QColor(colors[pos]) - # mean bar high - mean_y1 = int((val - min_value) * y_alpha) - # Draw bar border - p.setPen(QColor("black")) - - # Fill bar with custom color - p.fillRect(x1, height - mean_y1, x_alpha, mean_y1 - 1, QBrush(color)) - - # Draw error bars - if std != 0: - dev_up_y1 = int((val + std - min_value) * y_alpha) - dev_down_y1 = int((val - std - min_value) * y_alpha) - center_x = x1 + (x_alpha / 2) - p.drawLine(center_x, height - dev_up_y1, center_x, height - dev_down_y1) - p.drawLine(center_x + 1, height - dev_up_y1, center_x -1, height - dev_up_y1) - p.drawLine(center_x + 1, height - dev_down_y1, center_x -1, height - dev_down_y1) - - - -class QGraphicsTriangleItem(QGraphicsPolygonItem): - def __init__(self, width, height, orientation=1): - tri = QPolygonF() - if orientation == 1: - tri.append(QPointF(0, 0)) - tri.append(QPointF(0, height)) - tri.append(QPointF(width, height / 2.0)) - tri.append(QPointF(0, 0)) - elif orientation == 2: - tri.append(QPointF(0, 0)) - tri.append(QPointF(width, 0)) - tri.append(QPointF(width / 2.0, height)) - tri.append(QPointF(0, 0)) - elif orientation == 3: - tri.append(QPointF(0, height / 2.0)) - tri.append(QPointF(width, 0)) - tri.append(QPointF(width, height)) - tri.append(QPointF(0, height / 2.0)) - elif orientation == 4: - tri.append(QPointF(0, height)) - tri.append(QPointF(width, height)) - tri.append(QPointF(width / 2.0, 0)) - tri.append(QPointF(0, height)) - - QGraphicsPolygonItem.__init__(self, tri) - -class QGraphicsDiamondItem(QGraphicsPolygonItem): - def __init__(self, width, height): - pol = QPolygonF() - pol.append(QPointF(width / 2.0, 0)) - pol.append(QPointF(width, height / 2.0)) - pol.append(QPointF(width / 2.0, height)) - pol.append(QPointF(0, height / 2.0)) - pol.append(QPointF(width / 2.0, 0)) - QGraphicsPolygonItem.__init__(self, pol) - -class QGraphicsRoundRectItem(QGraphicsRectItem): - def __init__(self, *args, **kargs): - QGraphicsRectItem.__init__(self, *args, **kargs) - def paint(self, p, option, widget): - p.setPen(self.pen()) - p.setBrush(self.brush()) - p.drawRoundedRect(self.rect(), 3, 3) - -class SequenceItem(QGraphicsRectItem): - def __init__(self, seq, seqtype="aa", poswidth=1, posheight=10, - draw_text=False): - QGraphicsRectItem.__init__(self) - self.seq = seq - self.seqtype = seqtype - self.poswidth = poswidth - self.posheight = posheight - if draw_text: - self.poswidth = self.posheight = max(poswidth, posheight) - self.draw_text = draw_text - if seqtype == "aa": - self.fg = _aafgcolors - self.bg = _aabgcolors - elif seqtype == "nt": - self.fg = _ntfgcolors - self.bg = _ntbgcolors - self.setRect(0, 0, len(seq) * poswidth, posheight) - - def paint(self, p, option, widget): - x, y = 0, 0 - qfont = QFont("Courier") - for letter in self.seq: - br = QBrush(QColor(self.bg.get(letter, "white"))) - p.fillRect(x, 0, self.poswidth-1, self.posheight, br) - if letter == "-" or letter == ".": - p.drawLine(x, self.posheight/2, x+self.poswidth, self.posheight/2) - elif self.draw_text and self.poswidth >= 8: - qfont.setPixelSize(self.poswidth) - p.setFont(qfont) - p.setBrush(QBrush(QColor("black"))) - p.drawText(x + self.poswidth * 0.1, self.posheight *0.9, letter) - - else: - p.fillRect(x, 0, max(1, self.poswidth), self.posheight, br) - x += self.poswidth - - -class TextLabelItem(QGraphicsRectItem): - def __init__(self, text, rect, fcolor="black", ffam="Arial", fsize=10): - QGraphicsRectItem.__init__(self, rect) - self.text = text - self.fsize = int(fsize) - self.ffam = ffam - self.fcolor = fcolor - def paint(self, p, option, widget): - color = QColor(self.fcolor) - p.setPen(color) - p.setBrush(QBrush(color)) - qfont = QFont() - qfont.setFamily(self.ffam) - qfont.setPointSize(self.fsize) - p.setFont(qfont) - p.drawText(self.rect(), Qt.AlignCenter | Qt.AlignVCenter, self.text) - #p.setBrush(Qt.NoBrush) - #p.drawRect(self.rect()) - -class SeqMotifFace(StaticItemFace): - """.. versionadded:: 2.2 - - Creates a face based on an amino acid or nucleotide sequence and a - list of motif regions. - - :param None seq: a text string containing an aa or nt sequence. If - not provided, ``seq`` and ``compactseq`` motif modes will not be - available. - - :param None motifs: a list of motif regions referred to original - sequence. Each motif is defined as a list containing the - following information: - - :: - - motifs = [[seq.start, seq.end, shape, width, height, fgcolor, bgcolor], - [seq.start, seq.end, shape, width, height, fgcolor, bgcolor], - ... - ] - - Where: - - * **seq.start:** Motif start position referred to the full sequence - * **seq.end:** Motif end position referred to the full sequence - * **shape:** Shape used to draw the motif. Available values are: - - * ``o`` = circle or ellipse - * ``>`` = triangle (base to the left) - * ``<`` = triangle (base to the left) - * ``^`` = triangle (base at bottom) - * ``v`` = triangle (base on top ) - * ``<>`` = diamond - * ``[]`` = rectangle - * ``()`` = round corner rectangle - * ``seq`` = Show a color and the corresponding letter of each sequence position - * ``compactseq`` = Show a color for each sequence position - - * **width:** total width of the motif (or sequence position width if seq motif type) - * **height:** total height of the motif (or sequence position height if seq motif type) - * **fgcolor:** color for the motif shape border - * **bgcolor:** motif background color. Color code or name can be preceded with the "rgradient:" tag to create a radial gradient effect. - - :param line intermotif_format: How should spaces among motifs be filled. Available values are: "line", "blank", "none" and "seq", "compactseq". - :param none seqtail_format: How should remaining tail sequence be drawn. Available values are: "line", "seq", "compactseq" or "none" - :param compactseq seq_format: How should sequence be rendered in case no motif regions are provided. Available values are: "seq" and "compactseq" - """ - - def __init__(self, seq=None, motifs=None, seqtype="aa", - intermotif_format="line", seqtail_format="compactseq", - seq_format="compactseq", scale_factor=1): - - StaticItemFace.__init__(self, None) - self.seq = seq or [] - self.scale_factor = scale_factor - self.motifs = motifs - self.overlaping_motif_opacity = 0.7 - self.adjust_to_text = False - self.intermotif_format = intermotif_format - self.seqtail_format = seqtail_format - self.seq_format = seq_format - if seqtype == "aa": - self.fg = _aafgcolors - self.bg = _aabgcolors - elif seqtype == "nt": - self.fg = _ntfgcolors - self.bg = _ntbgcolors - - self.build_regions() - - - def build_regions(self): - # Sort regions - seq = self.seq or [] - motifs = self.motifs - if not motifs: - if self.seq_format == "seq": - motifs = [[1, len(seq), "seq", 10, 10, None, None, None]] - elif self.seq_format == "compactseq": - motifs = [[1, len(seq), "compactseq", 1, 10, None, None, None]] - motifs.sort() - intermotif = self.intermotif_format - self.regions = [] - current_seq_pos = 0 - for index, mf in enumerate(motifs): - start, end, typ, w, h, fg, bg, name = mf - start -= 1 - if start > current_seq_pos: - if intermotif == "blank": - self.regions.append([current_seq_pos, start, " ", 1, 1, None, None, None]) - elif intermotif == "line": - self.regions.append([current_seq_pos, start, "-", 1, 1, "black", None, None]) - elif intermotif == "seq": - # Colors are read from built-in dictionary - self.regions.append([current_seq_pos, start, "seq", 10, 10, None, None, None]) - elif intermotif == "compactseq": - # Colors are read from built-in dictionary - self.regions.append([current_seq_pos, start, "compactseq", 1, 10, None, None, None]) - elif intermotif == "none": - self.regions.append([current_seq_pos, start, " ", 0, 0, None, None, None]) - self.regions.append(mf) - current_seq_pos = max(current_seq_pos, end) - - if len(seq) > end: - if self.seqtail_format == "line": - self.regions.append([end, len(seq), "-", 1, 1, "black", None, None]) - elif self.seqtail_format == "seq": - self.regions.append([end, len(seq), "seq", 10, 10, None, None, None]) - elif self.seqtail_format == "compactseq": - self.regions.append([end, len(seq), "compactseq", 1, 10, None, None, None]) - - def update_items(self): - self.item = QGraphicsRectItem() - - max_h = max([reg[4] for index, reg - in enumerate(self.regions)]) - y_center = max_h / 2 - - max_x_pos = 0 - current_seq_end = 0 - for index, (start, end, typ, wf, h, fg, bg, name) in enumerate(self.regions): - real_start, real_end = start, end - if self.scale_factor != 1: - start *= self.scale_factor - end *= self.scale_factor - if wf: - wf *= self.scale_factor - - opacity = 1 - w = end-start - xstart = max_x_pos - - overlap_factor = 0 - if current_seq_end > start: - # calculates length for overlap - overlap_factor = float(current_seq_end - start) / (end-start) - if overlap_factor > 1: - continue - #xstart -= w * overlap_factor - else: - w = end - current_seq_end - - opacity = self.overlaping_motif_opacity - - y_start = y_center - (h/2) - if typ == "-": - x_end = xstart + w - i = QGraphicsLineItem(xstart, y_center, x_end, y_center) - elif typ == " ": - w = w * (end - start) - i = None - elif typ == "o": - i = QGraphicsEllipseItem(xstart, y_start, w, h) - elif typ == ">": - i = QGraphicsTriangleItem(w, h, orientation=1) - i.setPos(xstart, y_start) - elif typ == "v": - i = QGraphicsTriangleItem(w, h, orientation=2) - i.setPos(xstart, y_start) - elif typ == "<": - i = QGraphicsTriangleItem(w, h, orientation=3) - i.setPos(xstart, y_start) - elif typ == "^": - i = QGraphicsTriangleItem(w, h, orientation=4) - i.setPos(xstart, y_start) - elif typ == "<>": - i = QGraphicsDiamondItem(w, h) - i.setPos(xstart, y_start) - elif typ == "[]": - i = QGraphicsRectItem(xstart, y_start, w, h) - elif typ == "()": - i = QGraphicsRoundRectItem(xstart, y_start, w, h) - elif typ == "seq" and self.seq: - i = SequenceItem(self.seq[real_start:real_end], poswidth=wf, - posheight=h, draw_text=True) - w = i.rect().width() - h = i.rect().height() - i.setPos(xstart, y_center - (h/2.0)) - elif typ == "compactseq" and self.seq: - i = SequenceItem(self.seq[real_start:real_end], poswidth=wf, - posheight=h, draw_text=False) - w = i.rect().width() - h = i.rect().height() - i.setPos(xstart, y_center - (h/2.0)) - else: - i = QGraphicsSimpleTextItem("?") - - if i: - i.setParentItem(self.item) - - if bg: - if bg.startswith("rgradient:"): - rect = i.boundingRect() - gr = QRadialGradient(rect.center(), rect.width()/2) - gr.setColorAt(0, QColor("white")) - bg = bg.replace("rgradient:", "") - gr.setColorAt(1, QColor(bg)) - i.setBrush(gr) - else: - i.setBrush(QColor(bg)) - if fg: - i.setPen(QColor(fg)) - - if opacity < 1: - i.setOpacity(opacity) - - if name: - valid_h = max_h - family, fsize, fcolor, text = name.split("|") - #qfmetrics = QFontMetrics(qfont) - #txth = qfmetrics.height() - #txtw = qfmetrics.width(text) - txt_item = TextLabelItem(text, QRectF(0, 0, w, valid_h), - fsize=fsize, ffam=family, fcolor=fcolor) - # enlarges circle domains to fit text - #if typ == "o": - # min_r = math.hypot(txtw/2.0, txth/2.0) - # txtw = max(txtw, min_r*2) - - y_txt_start = (max_h/2.0) - (valid_h/2.0) - txt_item.setParentItem(self.item) - txt_item.setPos(xstart, y_txt_start) - - - if overlap_factor < 1: - max_x_pos = max(max_x_pos, max_x_pos + w) - current_seq_end = max(end, current_seq_end) - - self.item.setRect(0, 0, xstart, max_h) - self.item.setPen(QPen(Qt.NoPen)) - - - - -class SequencePlotFace(StaticItemFace): - """ - To draw plots, usually correlated to columns in alignment - - :argument values : a list of values - :argument None errors : a list of errors associated to each value. elements of the list can contain a list with lower and upper error, if they are different. - :argument None colors : a list of colors associated to each value - :argument None header : a title for the plot - :argument bar kind : kind of plot, one of bar, curve or sticks. - :argument None fsize : font size for header and labels - :argument 100 height : height of the plot (excluding labels) - :argument None hlines : list of y values of horizontal dashed lines to be drawn across plot - :argument None hlines_col: list of colors associated to each horizontal line - :argument None col_width : width of a column in the alignment - :argument red error_col : color of error bars - """ - def __init__(self, values, errors=None, colors=None, header='', - fsize=9, height = 100, hlines=None, kind='bar', - hlines_col = None, extras=None, col_width=11, - ylim=None, xlabel='', ylabel=''): - - self.col_w = float(col_width) - self.height = height - self.values = [float(v) for v in values] - self.width = self.col_w * len (self.values) - self.errors = errors if errors else [] - self.colors = colors if colors else ['gray'] * len(self.values) - self.header = header - self.fsize = fsize - if ylim: - self.ylim = tuple((float(y) for y in ylim)) - else: - dif = (max(self.values) - min(self.values))/20 - if dif >= 1: - self.ylim = (int(min(self.values)-0.5), int(max(self.values)+0.5)) - else: - from math import log10 - exp = str(-int(log10(min(self.values))-0.5)) - self.ylim = (float(int(min(self.values)*float('1e'+exp)-0.5))/float('1e'+exp), - float(int(max(self.values)/float('1e'+exp)+0.5))/float('1e'+exp)) - self.xlabel = xlabel - self.ylabel = ylabel - - if self.errors: - if type(self.errors[0]) is list or type(self.errors[0]) is tuple: - self._up_err = [float(e[1]) for e in self.errors] - self._dw_err = [float(-e[0]) for e in self.errors] - else: - self._up_err = [float(e) for e in self.errors] - self._dw_err = [float(-e) for e in self.errors] - if kind == 'bar': - self.draw_fun = self.draw_bar - elif kind == 'stick': - self.draw_fun = self.draw_stick - elif kind == 'curve': - self.draw_fun = self.draw_curve - else: - raise('kind %s not yet implemented... ;)'%kind) - - self.hlines = [float(h) for h in hlines] if hlines else [1.0] - self.hlines_col = hlines_col if hlines_col else ['black']*len(self.hlines) - - self.extras = extras if extras else [''] - if len (self.extras) != len (self.values): - self.extras = [''] - - super(SequencePlotFace, - self).__init__(QGraphicsRectItem(-40, 0, self.width+40, - self.height+50)) - self.item.setPen(QPen(QColor('white'))) - - def update_items(self): - # draw lines - for line, col in zip(self.hlines, self.hlines_col): - self.draw_hlines(line, col) - # draw plot - width = self.col_w - for i, val in enumerate(self.values): - self.draw_fun(width * i + self.col_w / 2 , val, i) - # draw error bars - if self.errors: - for i in range(len(self.errors)): - self.draw_errors(width * i + self.col_w / 2 , i) - # draw x axis - self.draw_x_axis() - # draw y axis - self.draw_y_axis() - # put header - self.write_header() - - def write_header(self): - text = QGraphicsSimpleTextItem(self.header) - text.setFont(QFont("Arial", self.fsize)) - text.setParentItem(self.item) - text.setPos(0, 5) - - def draw_y_axis(self): - lineItem = QGraphicsLineItem(0, self.coordY(self.ylim[0]), - 0, self.coordY(self.ylim[1]), - parent=self.item) - lineItem.setPen(QPen(QColor('black'))) - lineItem.setZValue(10) - max_w = 0 - for y in set(self.hlines + list(self.ylim)): - lineItem = QGraphicsLineItem(0, self.coordY(y), - -5, self.coordY(y), - parent=self.item) - lineItem.setPen(QPen(QColor('black'))) - lineItem.setZValue(10) - text = QGraphicsSimpleTextItem(str(y)) - text.setFont(QFont("Arial", self.fsize-2)) - text.setParentItem(self.item) - tw = text.boundingRect().width() - max_w = tw if tw > max_w else max_w - th = text.boundingRect().height() - # Center text according to masterItem size - text.setPos(-tw - 5, self.coordY(y)-th/2) - if self.ylabel: - text = QGraphicsSimpleTextItem(self.ylabel) - text.setFont(QFont("Arial", self.fsize-1)) - text.setParentItem(self.item) - text.rotate(-90) - tw = text.boundingRect().width() - th = text.boundingRect().height() - # Center text according to masterItem size - text.setPos(-th -5-max_w, tw/2+self.coordY(sum(self.ylim)/2)) - - def draw_x_axis(self): - lineItem = QGraphicsLineItem(self.col_w/2, - self.coordY(self.ylim[0])+2, - self.width-self.col_w/2, - self.coordY(self.ylim[0])+2, - parent=self.item) - lineItem.setPen(QPen(QColor('black'))) - lineItem.setZValue(10) - all_vals = range(0, len(self.values), 5) - if (len(self.values)-1)%5: - all_vals += [len(self.values)-1] - for x in all_vals: - lineItem = QGraphicsLineItem(0, self.coordY(self.ylim[0])+2, - 0, self.coordY(self.ylim[0])+6, - parent=self.item) - lineItem.setX(x*self.col_w + self.col_w/2) - lineItem.setPen(QPen(QColor('black'))) - lineItem.setZValue(10) - text = QGraphicsSimpleTextItem(str(x)) - text.setFont(QFont("Arial", self.fsize-2)) - text.setParentItem(self.item) - tw = text.boundingRect().width() - # Center text according to masterItem size - text.setPos(x*self.col_w-tw/2 + self.col_w/2, - self.coordY(self.ylim[0])+6) - - def coordY(self, y): - """ - return the transformation of Y according to mean value - (that is last element of lines) - """ - y_offset = 30 - if self.ylim[1] <= y: return y_offset - if self.ylim[1] == 0: return self.height + y_offset - if self.ylim[0] >= y: return self.height + y_offset - #return self.height - y * self.height / self.ylim[1] - return self.height + y_offset - (y-self.ylim[0]) / (self.ylim[1]-self.ylim[0]) * self.height - - def draw_hlines (self, line, col): - lineItem = QGraphicsLineItem(0, self.coordY(line), - self.width, self.coordY(line), - parent=self.item) - lineItem.setPen(QPen(QColor(col), 1, Qt.DashLine)) - lineItem.setZValue(10) - - def draw_bar(self, x, y, i): - h = self.coordY(self.ylim[0])#self.height - coordY = self.coordY - item = self.item - # if value stands out of bound - if y < self.ylim[0]: return - if y < self.ylim[1]: - # left line - lineItem = QGraphicsLineItem(0, h, 0, coordY(y), parent=item) - lineItem.setX(x-3) - lineItem.setPen(QPen(QColor(self.colors[i]),2)) - # right line - lineItem = QGraphicsLineItem(0, h, 0, coordY(y), parent=item) - lineItem.setX(x+3) - lineItem.setPen(QPen(QColor(self.colors[i]),2)) - # top line - lineItem = QGraphicsLineItem(0, coordY(y), 6, coordY(y), parent=item) - lineItem.setX(x-3) - lineItem.setPen(QPen(QColor(self.colors[i]),2)) - else: - # lower left line - lineItem = QGraphicsLineItem(0, h, 0, coordY(y), parent=item) - lineItem.setX(x-3) - lineItem.setPen(QPen(QColor(self.colors[i]),2)) - # lower right line - lineItem = QGraphicsLineItem(0, h, 0, coordY(y), parent=item) - lineItem.setX(x+3) - lineItem.setPen(QPen(QColor(self.colors[i]),2)) - # upper left line - lineItem = QGraphicsLineItem(0, coordY(y)-4, 0, coordY(y)-7, parent=item) - lineItem.setX(x-3) - lineItem.setPen(QPen(QColor(self.colors[i]),2)) - # upper right line - lineItem = QGraphicsLineItem(0, coordY(y)-4, 0, coordY(y)-7, parent=item) - lineItem.setX(x+3) - lineItem.setPen(QPen(QColor(self.colors[i]),2)) - # top line - lineItem = QGraphicsLineItem(0, coordY(y)-7, 6, coordY(y)-7, parent=item) - lineItem.setX(x-3) - lineItem.setPen(QPen(QColor(self.colors[i]),2)) - - def draw_stick(self, x, y, i): - lineItem = QGraphicsLineItem(0, self.coordY(self.ylim[0]), - 0, self.coordY(y), - parent=self.item) - lineItem.setX(x) - lineItem.setPen(QPen(QColor(self.colors[i]),2)) - - def draw_errors(self, x, i): - lower = self.values[i]+self._dw_err[i] - upper = self.values[i]+self._up_err[i] - lineItem = QGraphicsLineItem(0, self.coordY(lower), 0, - self.coordY(upper), parent=self.item) - lineItem.setX(x) - lineItem.setPen(QPen(QColor('black'),1)) - - def draw_curve(self, x, y, i): - # top line - lineItem = QGraphicsLineItem(0, self.coordY(y), 4, - self.coordY(y), parent=self.item) - lineItem.setX(x-2) - lineItem.setPen(QPen(QColor(self.colors[i]),2)) - if i > 0: - prev = self.values[i-1] if i>0 else self.values[i] - lineItem = QGraphicsLineItem(0, self.coordY(prev), self.col_w-4, - self.coordY(y), parent=self.item) - lineItem.setX(x - self.col_w+2) - lineItem.setPen(QPen(QColor(self.colors[i]),2)) - - - -class SequenceFace(StaticItemFace, Face): - """ - Creates a new molecular sequence face object. - :param seq: Sequence string to be drawn - :param seqtype: Type of sequence: "nt" or "aa" - :param fsize: Font size, (default=10) - - You can set custom colors for amino-acids or nucleotides: - - :param None codon: a string that corresponds to the reverse - translation of the amino-acid sequence - :param None col_w: width of the column (if col_w is lower than - font size, letter wont be displayed) - :param None fg_colors: dictionary of colors for foreground, with - as keys each possible character in sequences, and as value the - colors - :param None bg_colors: dictionary of colors for background, with - as keys each possible character in sequences, and as value the - colors - :param 3 alt_col_w: works together with special_col option, - defines the width of given columns - :param None special_col: list of lists containing the bounds - of columns to be displayed with alt_col_w as width - :param False interactive: more info can be displayed when - mouse over sequence - - """ - def __init__(self, seq, seqtype="aa", fsize=10, - fg_colors=None, bg_colors=None, - codon=None, col_w=None, alt_col_w=3, - special_col=None, interactive=False): - self.seq = seq - self.codon = codon - self.fsize = fsize - self.style = seqtype - self.col_w = float(self.fsize + 1) if col_w is None else float(col_w) - self.alt_col_w = float(alt_col_w) - self.special_col = special_col if special_col else [] - self.width = 0 # will store the width of the whole sequence - self.interact = interactive - - if self.style == "aa": - if not fg_colors: - fg_colors = _aafgcolors - if not bg_colors: - bg_colors = _aabgcolors - else: - if not fg_colors: - fg_colors = _ntfgcolors - if not bg_colors: - bg_colors = _ntbgcolors - - def __init_col(color_dic): - """to speed up the drawing of colored rectangles and characters""" - new_color_dic = {} - for car in color_dic: - new_color_dic[car] = QBrush(QColor(color_dic[car])) - return new_color_dic - - self.fg_col = __init_col(fg_colors) - self.bg_col = __init_col(bg_colors) - - # for future? - self.row_h = 13.0 - - super(SequenceFace, - self).__init__(QGraphicsRectItem(0, 0, self.width, - self.row_h)) - - - def update_items(self): - #self.item = QGraphicsRectItem(0,0,self._total_w, self.row_h) - seq_width = 0 - nopen = QPen(Qt.NoPen) - font = QFont("Courier", self.fsize) - rect_cls = self.InteractiveLetterItem if self.interact \ - else QGraphicsRectItem - for i, letter in enumerate(self.seq): - width = self.col_w - for reg in self.special_col: - if reg[0] < i <= reg[1]: - width = self.alt_col_w - break - #load interactive item if called correspondingly - rectitem = rect_cls(0, 0, width, self.row_h, parent=self.item) - rectitem.setX(seq_width) # to give correct X to children item - rectitem.setBrush(self.bg_col[letter]) - rectitem.setPen(nopen) - if self.interact: - if self.codon: - rectitem.codon = '%s, %d: %s' % (self.seq[i], i, - self.codon[i*3:i*3+3]) - else: - rectitem.codon = '%s, %d' % (self.seq[i], i) - # write letter if enough space - if width >= self.fsize: - text = QGraphicsSimpleTextItem(letter, parent=rectitem) - text.setFont(font) - text.setBrush(self.fg_col[letter]) - # Center text according to rectitem size - txtw = text.boundingRect().width() - txth = text.boundingRect().height() - text.setPos((width - txtw)/2, (self.row_h - txth)/2) - seq_width += width - self.width = seq_width - - class InteractiveLetterItem(QGraphicsRectItem): - """This is a class""" - def __init__(self, *arg, **karg): - QGraphicsRectItem.__init__(self, *arg, **karg) - self.codon = None - self.label = None - self.setAcceptsHoverEvents(True) - - def hoverEnterEvent (self, e): - """ when mouse is over""" - if not self.label: - self.label = QGraphicsRectItem(parent=self) - #self.label.setY(-18) - self.label.setX(11) - self.label.setBrush(QBrush(QColor("white"))) - self.label.text = QGraphicsSimpleTextItem(parent=self.label) - - self.setZValue(1) - self.label.text.setText(self.codon) - self.label.setRect(self.label.text.boundingRect()) - self.label.setVisible(True) - - def hoverLeaveEvent(self, e): - """when mouse leaves area""" - if self.label: - self.label.setVisible(False) - self.setZValue(0) - diff --git a/ete2/treeview/faces.pyc b/ete2/treeview/faces.pyc deleted file mode 100644 index 7d376bc..0000000 Binary files a/ete2/treeview/faces.pyc and /dev/null differ diff --git a/ete2/treeview/layouts.py b/ete2/treeview/layouts.py deleted file mode 100644 index 4e4d522..0000000 --- a/ete2/treeview/layouts.py +++ /dev/null @@ -1,262 +0,0 @@ -__VERSION__="ete2-2.2rev1026" -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# - -import numpy -import faces - -def basic(node): - if node.is_leaf(): - #node.img_style["size"]=1 - #node.img_style["shape"] = "circle" - faces.add_face_to_node(faces.AttrFace("name","Arial",10,"#4f8f0f",None), node, 0 ) - -def phylogeny(node): - leaf_color = "#000000" - node.img_style["shape"] = "circle" - if hasattr(node,"evoltype"): - if node.evoltype == 'D': - node.img_style["fgcolor"] = "#FF0000" - node.img_style["hz_line_color"] = "#FF0000" - node.img_style["vt_line_color"] = "#FF0000" - elif node.evoltype == 'S': - node.img_style["fgcolor"] = "#1d176e" - node.img_style["hz_line_color"] = "#1d176e" - node.img_style["vt_line_color"] = "#1d176e" - elif node.evoltype == 'L': - node.img_style["fgcolor"] = "#777777" - node.img_style["vt_line_color"] = "#777777" - node.img_style["hz_line_color"] = "#777777" - node.img_style["hz_line_type"] = 1 - node.img_style["vt_line_type"] = 1 - leaf_color = "#777777" - - if node.is_leaf(): - node.img_style["shape"] = "square" - node.img_style["size"] = 4 - node.img_style["fgcolor"] = leaf_color - faces.add_face_to_node( faces.AttrFace("name","Arial",11,leaf_color,None), node, 0 ) - if hasattr(node,"sequence"): - SequenceFace = faces.SequenceFace(node.sequence,"aa",13) - faces.add_face_to_node(SequenceFace, node, 1, aligned=True) - else: - node.img_style["size"] = 6 - -def heatmap(node): - square_size = 10 - # Extras node info - node.collapsed = False - - # Color and style - node.img_style["fgcolor"] = "#3333FF" - node.img_style["size"] = 0 - - ncols = node.arraytable.matrix.shape[1] - - matrix_max = numpy.max(node.arraytable._matrix_max) - matrix_min = numpy.min(node.arraytable._matrix_min) - print matrix_max - matrix_avg = matrix_min+((matrix_max-matrix_min)/2) - - ProfileFace = faces.ProfileFace(\ - matrix_max,\ - matrix_min,\ - matrix_avg,\ - square_size*ncols,\ - square_size,\ - "heatmap") - ProfileFace.ymargin=0 - if node.is_leaf(): - # Set colors - faces.add_face_to_node(ProfileFace, node, 0, aligned=True ) - -def cluster_cbars(node): - # Extras node info - node.collapsed = False - # Color and style - node.img_style["fgcolor"] = "#3333FF" - node.img_style["size"] = 4 - matrix_max = numpy.max(node.arraytable._matrix_max) - matrix_min = numpy.min(node.arraytable._matrix_min) - matrix_avg = matrix_min+((matrix_max-matrix_min)/2) - ProfileFace = faces.ProfileFace(\ - matrix_max,\ - matrix_min,\ - matrix_avg,\ - 200,\ - 60,\ - "cbars") - - if node.is_leaf(): - nameFace = faces.AttrFace("name",fsize=6 ) - faces.add_face_to_node(nameFace, node, 1, aligned=True ) - faces.add_face_to_node(ProfileFace, node, 0, aligned=True ) - else: - # Set custom faces - faces.add_face_to_node(ProfileFace, node, 0, aligned=True ) - -def cluster_lines(node): - # Extras node info - node.collapsed = False - # Color and style - node.img_style["fgcolor"] = "#3333FF" - node.img_style["size"] = 4 - matrix_max = numpy.max(node.arraytable._matrix_max) - matrix_min = numpy.min(node.arraytable._matrix_min) - matrix_avg = matrix_min+((matrix_max-matrix_min)/2) - ProfileFace = faces.ProfileFace(\ - matrix_max,\ - matrix_min,\ - matrix_avg,\ - 200,\ - 50,\ - "lines") - - if node.is_leaf(): - nameFace = faces.AttrFace("name",fsize=6 ) - faces.add_face_to_node(nameFace, node, 1, aligned=True ) - faces.add_face_to_node(ProfileFace, node, 0, aligned=True ) - else: - # Set custom faces - faces.add_face_to_node(ProfileFace, node, 0, aligned=True ) - -def cluster_bars(node): - # Extras node info - node.collapsed = False - # Color and style - node.img_style["fgcolor"] = "#3333FF" - node.img_style["size"] = 4 - - if node.is_leaf(): - matrix_max = numpy.max(node.arraytable._matrix_max) - matrix_min = numpy.min(node.arraytable._matrix_min) - matrix_avg = matrix_min+((matrix_max-matrix_min)/2) - ProfileFace = faces.ProfileFace(\ - matrix_max,\ - matrix_min,\ - matrix_avg,\ - 200,\ - 40,\ - "bars") - nameFace = faces.AttrFace("name",fsize=6 ) - faces.add_face_to_node(nameFace, node, 1, aligned=True ) - faces.add_face_to_node(ProfileFace, node, 0, aligned=True ) - -def large(node): - # Color and style - node.img_style["fgcolor"] = "#3333FF" - node.img_style["size"] = 0 - - -def evol_layout(node): - ''' - layout for CodemlTree - ''' - if hasattr(node, "collapsed"): - if node.collapsed == 1: - node.img_style["draw_descendants"]= False - leaf_color = "#000000" - if not node.is_root() and 'w' in node.features: - node.img_style["shape"] = 'circle' - if (node.w > 900): - node._w = 3 - elif (node.w > 100): - node._w = 2.5 - elif (node.w > 10) : - node._w = 2 - elif (node.w > 1): - node._w = 1.5 - else: - node._w = node.w - node.img_style["size"] = int ((float(node._w))*6+2) - if node._w == 3 : - node.img_style["fgcolor"] = "#c10000" - if node._w == 2.5 : - node.img_style["fgcolor"] = "#FF5A02" - if node._w == 2 : - node.img_style["fgcolor"] = "#FFA200" - if node._w == 1.5 : - node.img_style["fgcolor"] = "#E9BF00" - if node._w < 0.2 : - node.img_style["fgcolor"] = "#000000" - if hasattr(node,"extras"): - faces.add_face_to_node( faces.AttrFace("extras", "Arial", 7, \ - "#000000", None), node, 2 ) - #if node.is_leaf(): - if hasattr (node, "sequence"): - seqface = faces.SequenceFace(node.sequence, interactive=True, - codon=node.nt_sequence) - faces.add_face_to_node(seqface, node, 1, aligned=True) - - -def evol_clean_layout(node): - ''' - layout for CodemlTree - ''' - if hasattr(node, "collapsed"): - if node.collapsed == 1: - node.img_style["draw_descendants"]= False - leaf_color = "#000000" - node.img_style["size"] = 2 - if node.is_leaf(): - #if hasattr (node,"highlight"): - # faces.add_face_to_node(faces.AttrFace("name", "Arial", 9, \ - # node.highlight, - # None), \ - # node, 0 ) - #else: - # leaface = faces.AttrFace("name", "Arial", 9, leaf_color, None) - # leaface.margin_right = 10 - # faces.add_face_to_node (leaface, node, 0) - if hasattr (node, "sequence"): - seqface = faces.SequenceFace(node.sequence, interactive=True, - codon=node.nt_sequence) - faces.add_face_to_node(seqface, node, 1, aligned=True) - if hasattr (node, 'dN'): - faces.add_face_to_node (faces.TextFace('%.4f'%(node.w), fsize=6, - fgcolor="#7D2D2D"), - node, 0, position="branch-top") - faces.add_face_to_node (faces.TextFace('%.2f/%.2f'% (100*node.dN, - 100*node.dS), - fsize=6, fgcolor="#787878"), - node, 0, position="branch-bottom") - if hasattr(node,"extras"): - faces.add_face_to_node( faces.AttrFace("extras", "Arial", 7, \ - "#000000", None), node, 2 ) diff --git a/ete2/treeview/layouts.pyc b/ete2/treeview/layouts.pyc deleted file mode 100644 index 0118824..0000000 Binary files a/ete2/treeview/layouts.pyc and /dev/null differ diff --git a/ete2/treeview/main.py b/ete2/treeview/main.py deleted file mode 100644 index 264f68f..0000000 --- a/ete2/treeview/main.py +++ /dev/null @@ -1,745 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -import colorsys -import random -import re -import types -from sys import stderr - -from PyQt4.QtGui import * -from PyQt4 import QtCore - -from svg_colors import SVG_COLORS, COLOR_SCHEMES - -import time -def tracktime(f): - def a_wrapper_accepting_arguments(*args, **kargs): - t1 = time.time() - r = f(*args, **kargs) - print " -> TIME:", f.func_name, time.time() - t1 - return r - return a_wrapper_accepting_arguments - - -_LINE_TYPE_CHECKER = lambda x: x in (0,1,2) -_SIZE_CHECKER = lambda x: isinstance(x, int) -_COLOR_MATCH = re.compile("^#[A-Fa-f\d]{6}$") -_COLOR_CHECKER = lambda x: x.lower() in SVG_COLORS or re.match(_COLOR_MATCH, x) -_NODE_TYPE_CHECKER = lambda x: x in ["sphere", "circle", "square"] -_BOOL_CHECKER = lambda x: isinstance(x, bool) or x in (0,1) - -FACE_POSITIONS = set(["branch-right", "branch-top", "branch-bottom", "float", "float-behind", "aligned"]) - -__all__ = ["NodeStyle", "TreeStyle", "FaceContainer", "_leaf", "add_face_to_node", "COLOR_SCHEMES"] - -NODE_STYLE_DEFAULT = [ - ["fgcolor", "#0030c1", _COLOR_CHECKER ], - ["bgcolor", "#FFFFFF", _COLOR_CHECKER ], - ["node_bgcolor", "#FFFFFF", _COLOR_CHECKER ], - #["partition_bgcolor","#FFFFFF", _COLOR_CHECKER ], - ["faces_bgcolor", "#FFFFFF", _COLOR_CHECKER ], - ["vt_line_color", "#000000", _COLOR_CHECKER ], - ["hz_line_color", "#000000", _COLOR_CHECKER ], - ["hz_line_type", 0, _LINE_TYPE_CHECKER ], # 0 solid, 1 dashed, 2 dotted - ["vt_line_type", 0, _LINE_TYPE_CHECKER ], # 0 solid, 1 dashed, 2 dotted - ["size", 3, _SIZE_CHECKER ], # node circle size - ["shape", "circle", _NODE_TYPE_CHECKER ], - ["draw_descendants", True, _BOOL_CHECKER ], - ["hz_line_width", 0, _SIZE_CHECKER ], - ["vt_line_width", 0, _SIZE_CHECKER ] - ] - -TREE_STYLE_CHECKER = { - "mode": lambda x: x.lower() in set(["c", "r"]), - } - -# _faces and faces are registered to allow deepcopy to work on nodes -VALID_NODE_STYLE_KEYS = set([i[0] for i in NODE_STYLE_DEFAULT]) | set(["_faces"]) - -class _Border(object): - def __init__(self): - self.width = None - self.type = 0 - self.color = None - - def apply(self, item): - if self.width is not None: - r = item.boundingRect() - border = QGraphicsRectItem(r) - border.setParentItem(item) - pen = QPen() - set_pen_style(pen, self.type) - pen.setWidth(self.width) - pen.setCapStyle(QtCore.Qt.FlatCap) - pen.setColor(QColor(self.color)) - border.setPen(pen) - return border - else: - return None - -class _Background(object): - """ - Set the background of the object - - :param color: RGB color code or :data:`SVG_COLORS` - - """ - def __init__(self): - self.color = None - - def apply(self, item): - if self.color: - r = item.boundingRect() - bg = QGraphicsRectItem(r) - bg.setParentItem(item) - pen = QPen(QColor(self.color)) - brush = QBrush(QColor(self.color)) - bg.setPen(pen) - bg.setBrush(brush) - bg.setFlag(QGraphicsItem.ItemStacksBehindParent) - return bg - else: - return None - - -class _ActionDelegator(object): - """ Used to associate GUI Functions to nodes and faces """ - - def get_delegate(self): - return self._delegate - - def set_delegate(self, delegate): - if hasattr(delegate, "init"): - delegate.init(self) - - for attr in dir(delegate): - if not attr.startswith("_") and attr != "init" : - fn = getattr(delegate, attr) - setattr(self, attr, types.MethodType(fn, self)) - self._delegate = delegate - - delegate = property(get_delegate, set_delegate) - - def __init__(self): - self._delegate = None - -class NodeStyle(dict): - """ - .. versionadded:: 2.1 - - .. currentmodule:: ete2 - - A dictionary with all valid node graphical attributes. - - :argument #0030c1 fgcolor: RGB code or name in :data:`SVG_COLORS` - :argument #FFFFFF bgcolor: RGB code or name in :data:`SVG_COLORS` - :argument #FFFFFF node_bgcolor: RGB code or name in :data:`SVG_COLORS` - :argument #FFFFFF partition_bgcolor: RGB code or name in :data:`SVG_COLORS` - :argument #FFFFFF faces_bgcolor: RGB code or name in :data:`SVG_COLORS` - :argument #000000 vt_line_color: RGB code or name in :data:`SVG_COLORS` - :argument #000000 hz_line_color: RGB code or name in :data:`SVG_COLORS` - :argument 0 hz_line_type: integer number - :argument 0 vt_line_type: integer number - :argument 3 size: integer number - :argument "circle" shape: "circle", "square" or "sphere" - :argument True draw_descendants: Mark an internal node as a leaf. - - :argument 0 hz_line_width: integer number representing the width - of the line in pixels. A line width of - zero indicates a cosmetic pen. This - means that the pen width is always - drawn one pixel wide, independent of - the transformation set on the painter. - - :argument 0 vt_line_width: integer number representing the width - of the line in pixels. A line width of - zero indicates a cosmetic pen. This - means that the pen width is always - drawn one pixel wide, independent of - the transformation set on the painter. - - """ - - def __init__(self, *args, **kargs): - super(NodeStyle, self).__init__(*args, **kargs) - self.init() - #self._block_adding_faces = False - - def init(self): - for key, dvalue, checker in NODE_STYLE_DEFAULT: - if key not in self: - self[key] = dvalue - elif not checker(self[key]): - raise ValueError("'%s' attribute in node style has not a valid value: %s" %\ - (key, self[key])) - # - # #super(NodeStyle, self).__setitem__("_faces", {}) - # # copy fixed faces to the faces dict that will be drawn - # #for pos, values in self["faces"].iteritems(): - # # for col, faces in values.iteritems(): - # # self["_faces"].setdefault(pos, {}) - # # self["_faces"][pos][col] = list(faces) - - def __setitem__(self, i, v): - # keeps compatible with ETE 2.0 version - if i == "line_type": - print >>stderr, "WARNING: [%s] keyword is deprecated and it has been replaced by %s." %\ - (i, "[hz_line_type, vt_line_type]") - print >>stderr, "WARNING: Support for this keyword will be removed in next ETE versions." - super(NodeStyle, self).__setitem__("hz_line_type", v) - i = "vt_line_type" - - if i == "vlwidth": - i = "vt_line_width" - print >>stderr, "WARNING: [%s] keyword is deprecated and it has been replaced by %s." %\ - (i, "[vt_line_width]") - print >>stderr, "WARNING: Support for this keyword will be removed in next ETE versions." - if i == "hlwidth": - i = "hz_line_width" - print >>stderr, "WARNING: [%s] keyword is deprecated and it has been replaced by %s." %\ - (i, "[hz_line_width]") - print >>stderr, "WARNING: Support for this keyword will be removed in next ETE versions." - - if i not in VALID_NODE_STYLE_KEYS: - raise ValueError("'%s' is not a valid keyword for a NodeStyle instance" %i) - - super(NodeStyle, self).__setitem__(i, v) - - #def clear(self): - # super(NodeStyle, self).__setitem__("_faces", {}) - -class TreeStyle(object): - """ - .. versionadded:: 2.1 - - .. currentmodule:: ete2 - - Contains all the general image properties used to render a tree - - **-- About tree design --** - - :param None layout_fn: Layout function used to dynamically control - the aspect of nodes. Valid values are: None or a pointer to a method, - function, etc. - - **-- About tree shape --** - - :param "r" mode: Valid modes are 'c'(ircular) or 'r'(ectangular). - - :param 0 orientation: If 0, tree is drawn from left-to-right. If - 1, tree is drawn from right-to-left. This property only makes - sense when "r" mode is used. - - :param 0 rotation: Tree figure will be rotate X degrees (clock-wise - rotation). - - :param 1 min_leaf_separation: Min separation, in pixels, between - two adjacent branches - - :param 0 branch_vertical_margin: Leaf branch separation margin, in - pixels. This will add a separation of X pixels between adjacent - leaf branches. In practice, increasing this value work as - increasing Y axis scale. - - :param 0 arc_start: When circular trees are drawn, this defines the - starting angle (in degrees) from which leaves are distributed - (clock-wise) around the total arc span (0 = 3 o'clock). - - :param 359 arc_span: Total arc used to draw circular trees (in - degrees). - - :param 0 margin_left: Left tree image margin, in pixels. - :param 0 margin_right: Right tree image margin, in pixels. - :param 0 margin_top: Top tree image margin, in pixels. - :param 0 margin_bottom: Bottom tree image margin, in pixels. - - **-- About Tree branches --** - - :param None scale: Scale used to draw branch lengths. If None, it will - be automatically calculated. - - :param "mid" optimal_scale_level: Two levels of automatic branch - scale detection are available: :attr:`"mid"` and - :attr:`"full"`. In :attr:`full` mode, branch scale will me - adjusted to fully avoid dotted lines in the tree image. In other - words, scale will be increased until the extra space necessary - to allocated all branch-top/bottom faces and branch-right faces - (in circular mode) is covered by real branches. Note, however, - that the optimal scale in trees with very unbalanced branch - lengths might be huge. If :attr:`"mid"` mode is selected (as it is by default), - optimal scale will only satisfy the space necessary to allocate - branch-right faces in circular trees. Some dotted lines - (artificial branch offsets) will still appear when - branch-top/bottom faces are larger than branch length. Note that - both options apply only when :attr:`scale` is set to None - (automatic). - - :param 0.25 root_opening_factor: (from 0 to 1). It defines how much the center of - a circular tree could be opened when adjusting optimal scale, referred - to the total tree length. By default (0.25), a blank space up to 4 - times smaller than the tree width could be used to calculate the - optimal tree scale. A 0 value would mean that root node should - always be tightly adjusted to the center of the tree. - - :param True complete_branch_lines_when_necessary: True or False. - Draws an extra line (dotted by default) to complete branch lengths when the space to cover is larger than the branch itself. - - :param 2 extra_branch_line_type: 0=solid, 1=dashed, 2=dotted - - :param "gray" extra_branch_line_color": RGB code or name in - :data:`SVG_COLORS` - - :param False force_topology: Convert tree branches to a fixed length, thus allowing to - observe the topology of tight nodes - - :param True draw_guiding_lines: Draw guidelines from leaf nodes - to aligned faces - - :param 2 guiding_lines_type: 0=solid, 1=dashed, 2=dotted. - - :param "gray" guiding_lines_color: RGB code or name in :data:`SVG_COLORS` - - **-- About node faces --** - - :param False allow_face_overlap: If True, node faces are not taken - into account to scale circular tree images, just like many other - visualization programs. Overlapping among branch elements (such - as node labels) will be therefore ignored, and tree size - will be a lot smaller. Note that in most cases, manual setting - of tree scale will be also necessary. - - :param True draw_aligned_faces_as_table: Aligned faces will be - drawn as a table, considering all columns in all node faces. - - :param True children_faces_on_top: When floating faces from - different nodes overlap, children faces are drawn on top of - parent faces. This can be reversed by setting this attribute - to false. - - **-- Addons --** - - :param False show_border: Draw a border around the whole tree - - :param True show_scale: Include the scale legend in the tree - image - - :param False show_leaf_name: Automatically adds a text Face to - leaf nodes showing their names - - :param False show_branch_length: Automatically adds branch - length information on top of branches - - :param False show_branch_support: Automatically adds branch - support text in the bottom of tree branches - - **-- Tree surroundings --** - - The following options are actually Face containers, so graphical - elements can be added just as it is done with nodes. In example, - to add tree legend: - - :: - - TreeStyle.legend.add_face(CircleFace(10, "red"), column=0) - TreeStyle.legend.add_face(TextFace("0.5 support"), column=1) - - :param aligned_header: a :class:`FaceContainer` aligned to the end - of the tree and placed at the top part. - - :param aligned_foot: a :class:`FaceContainer` aligned to the end - of the tree and placed at the bottom part. - - :param legend: a :class:`FaceContainer` with an arbitrary number of faces - representing the legend of the figure. - :param 4 legend_position=4: TopLeft corner if 1, TopRight - if 2, BottomLeft if 3, BottomRight if 4 - - :param title: A Face container that can be used as tree title - - """ - - def set_layout_fn(self, layout): - self._layout_handler = [] - if type(layout) not in set([list, set, tuple, frozenset]): - layout = [layout] - - for ly in layout: - # Validates layout function - if (type(ly) == types.FunctionType or type(ly) == types.MethodType or ly is None): - self._layout_handler.append(ly) - else: - import layouts - try: - self._layout_handler.append(getattr(layouts, ly)) - except Exception, e: - print e - raise ValueError ("Required layout is not a function pointer nor a valid layout name.") - - def get_layout_fn(self): - return self._layout_handler - - layout_fn = property(get_layout_fn, set_layout_fn) - - def __init__(self): - # ::::::::::::::::::::::::: - # TREE SHAPE AND SIZE - # ::::::::::::::::::::::::: - - # Valid modes are : "c" or "r" - self.mode = "r" - - # Applies only for circular mode. It prevents aligned faces to - # overlap each other by increasing the radius. - self.allow_face_overlap = False - - # Layout function used to dynamically control the aspect of - # nodes - self._layout_handler = [] - - # 0= tree is drawn from left-to-right 1= tree is drawn from - # right-to-left. This property only has sense when "r" mode - # is used. - self.orientation = 0 - - # Tree rotation in degrees (clock-wise rotation) - self.rotation = 0 - - # Scale used to convert branch lengths to pixels. If 'None', - # the scale will be automatically calculated. - self.scale = None - - # How much the center of a circular tree can be opened, - # referred to the total tree length. - self.root_opening_factor = 0.25 - - # mid, or full - self.optimal_scale_level = "mid" - - # Min separation, in pixels, between to adjacent branches - self.min_leaf_separation = 1 - - # Leaf branch separation margin, in pixels. This will add a - # separation of X pixels between adjacent leaf branches. In - # practice this produces a Y-zoom in. - self.branch_vertical_margin = 0 - - # When circular trees are drawn, this defines the starting - # angle (in degrees) from which leaves are distributed - # (clock-wise) around the total arc. 0 = 3 o'clock - self.arc_start = 0 - - # Total arc used to draw circular trees (in degrees) - self.arc_span = 359 - - # Margins around tree picture - self.margin_left = 1 - self.margin_right = 1 - self.margin_top = 1 - self.margin_bottom = 1 - - # ::::::::::::::::::::::::: - # TREE BRANCHES - # ::::::::::::::::::::::::: - - # When top-branch and bottom-branch faces are larger than - # branch length, branch line can be completed. Also, when - # circular trees are drawn, - self.complete_branch_lines_when_necessary = True - self.extra_branch_line_type = 2 # 0 solid, 1 dashed, 2 dotted - self.extra_branch_line_color = "gray" - - # Convert tree branches to a fixed length, thus allowing to - # observe the topology of tight nodes - self.force_topology = False - - # Draw guidelines from leaf nodes to aligned faces - self.draw_guiding_lines = True - - # Format and color for the guiding lines - self.guiding_lines_type = 2 # 0 solid, 1 dashed, 2 dotted - self.guiding_lines_color = "gray" - - # ::::::::::::::::::::::::: - # FACES - # ::::::::::::::::::::::::: - - # Aligned faces will be drawn as a table, considering all - # columns in all node faces. - self.draw_aligned_faces_as_table = True - self.aligned_table_style = 0 # 0 = full grid (rows and - # columns), 1 = semigrid ( rows - # are merged ) - - # When floating faces from different nodes overlap, children - # faces are drawn on top of parent faces. This can be reversed - # by setting this attribute to false. - self.children_faces_on_top = True - - # ::::::::::::::::::::::::: - # Addons - # ::::::::::::::::::::::::: - - # Draw a border around the whole tree - self.show_border = False - - # Draw the scale - self.show_scale = True - - # Initialize aligned face headers - self.aligned_header = FaceContainer() - self.aligned_foot = FaceContainer() - - self.show_leaf_name = True - self.show_branch_length = False - self.show_branch_support = False - - self.legend = FaceContainer() - self.legend_position = 2 - - - self.title = FaceContainer() - self.tree_width = 180 - # PRIVATE values - self._scale = None - - self.__closed__ = 1 - - - def __setattr__(self, attr, val): - if hasattr(self, attr) or not getattr(self, "__closed__", 0): - if TREE_STYLE_CHECKER.get(attr, lambda x: True)(val): - object.__setattr__(self, attr, val) - else: - raise ValueError("[%s] wrong type" %attr) - else: - raise ValueError("[%s] option is not supported" %attr) - -class _FaceAreas(object): - def __init__(self): - for a in FACE_POSITIONS: - setattr(self, a, FaceContainer()) - - def __setattr__(self, attr, val): - if attr not in FACE_POSITIONS: - raise AttributeError("Face area [%s] not in %s" %(attr, FACE_POSITIONS) ) - return super(_FaceAreas, self).__setattr__(attr, val) - - def __getattr__(self, attr): - if attr not in FACE_POSITIONS: - raise AttributeError("Face area [%s] not in %s" %(attr, FACE_POSITIONS) ) - return super(_FaceAreas, self).__getattr__(attr) - -class FaceContainer(dict): - """ - .. versionadded:: 2.1 - - Use this object to create a grid of faces. You can add faces to different columns. - """ - def add_face(self, face, column): - """ - add the face **face** to the specified **column** - """ - self.setdefault(int(column), []).append(face) - -def _leaf(node): - collapsed = hasattr(node, "_img_style") and not node.img_style["draw_descendants"] - return collapsed or node.is_leaf() - -def add_face_to_node(face, node, column, aligned=False, position="branch-right"): - """ - .. currentmodule:: ete2.treeview.faces - - Adds a Face to a given node. - - :argument face: A :class:`Face` instance - - .. currentmodule:: ete2 - - :argument node: a tree node instance (:class:`Tree`, :class:`PhyloTree`, etc.) - :argument column: An integer number starting from 0 - :argument "branch-right" position: Possible values are - "branch-right", "branch-top", "branch-bottom", "float", "float-behind" and "aligned". - """ - - ## ADD HERE SOME TYPE CHECK FOR node and face - - # to stay 2.0 compatible - if aligned == True: - position = "aligned" - - if getattr(node, "_temp_faces", None): - getattr(node._temp_faces, position).add_face(face, column) - else: - raise Exception("This function can only be called within a layout function. Use node.add_face() instead") - -def random_color(h=None, l=None, s=None): - def rgb2hex(rgb): - return '#%02x%02x%02x' % rgb - def hls2hex(h, l, s): - return rgb2hex( tuple(map(lambda x: int(x*255), colorsys.hls_to_rgb(h, l, s)))) - - if not h: - h = random.random() - if not s: - s = 0.5 - if not l: - l = 0.5 - return hls2hex(h, l, s) - -def set_pen_style(pen, line_style): - if line_style == 0: - pen.setStyle(QtCore.Qt.SolidLine) - elif line_style == 1: - pen.setStyle(QtCore.Qt.DashLine) - elif line_style == 2: - pen.setStyle(QtCore.Qt.DotLine) - - -def save(scene, imgName, w=None, h=None, dpi=90,\ - take_region=False, units="px"): - if imgName == "%%inline": - ipython_inline = True - ext = "SVG" - else: - ipython_inline = False - ext = imgName.split(".")[-1].upper() - - main_rect = scene.sceneRect() - aspect_ratio = main_rect.height() / main_rect.width() - - # auto adjust size - if not w and not h: - units = "px" - w = main_rect.width() - h = main_rect.height() - ratio_mode = QtCore.Qt.KeepAspectRatio - elif w and h: - ratio_mode = QtCore.Qt.IgnoreAspectRatio - elif h is None : - h = w * aspect_ratio - ratio_mode = QtCore.Qt.KeepAspectRatio - elif w is None: - w = h / aspect_ratio - ratio_mode = QtCore.Qt.KeepAspectRatio - - # Adjust to resolution - if units == "mm": - if w: - w = w * 0.0393700787 * dpi - if h: - h = h * 0.0393700787 * dpi - elif units == "in": - if w: - w = w * dpi - if h: - h = h * dpi - elif units == "px": - pass - else: - raise Exception("wrong unit format") - - if ext == "SVG": - from PyQt4 import QtSvg - svg = QtSvg.QSvgGenerator() - svg.setFileName(imgName) - targetRect = QtCore.QRectF(0, 0, w, h) - svg.setSize(QtCore.QSize(w, h)) - svg.setViewBox(targetRect) - svg.setTitle("Generated with ETE http://ete.cgenomics.org") - svg.setDescription("Generated with ETE http://ete.cgenomics.org") - - pp = QPainter() - pp.begin(svg) - scene.render(pp, targetRect, scene.sceneRect(), ratio_mode) - pp.end() - # Fix a very annoying problem with Radial gradients in - # inkscape and browsers... - temp_compatible_code = open(imgName).read().replace("xml:id=", "id=") - compatible_code = re.sub('font-size="(\d+)"', 'font-size="\\1pt"', temp_compatible_code) - if ipython_inline: - from IPython.core.display import SVG - return SVG(compatible_code) - else: - open(imgName, "w").write(compatible_code) - # End of fix - - elif ext == "PDF" or ext == "PS": - if ext == "PS": - format = QPrinter.PostScriptFormat - else: - format = QPrinter.PdfFormat - - printer = QPrinter(QPrinter.HighResolution) - printer.setResolution(dpi) - printer.setOutputFormat(format) - printer.setPageSize(QPrinter.A4) - printer.setPaperSize(QtCore.QSizeF(w, h), QPrinter.DevicePixel) - printer.setPageMargins(0, 0, 0, 0, QPrinter.DevicePixel) - - #pageTopLeft = printer.pageRect().topLeft() - #paperTopLeft = printer.paperRect().topLeft() - # For PS -> problems with margins - #print paperTopLeft.x(), paperTopLeft.y() - #print pageTopLeft.x(), pageTopLeft.y() - # print printer.paperRect().height(), printer.pageRect().height() - #topleft = pageTopLeft - paperTopLeft - - printer.setFullPage(True); - printer.setOutputFileName(imgName); - pp = QPainter(printer) - targetRect = QtCore.QRectF(0, 0 , w, h) - scene.render(pp, targetRect, scene.sceneRect(), ratio_mode) - else: - targetRect = QtCore.QRectF(0, 0, w, h) - ii= QImage(w, h, QImage.Format_ARGB32) - ii.fill(QColor(QtCore.Qt.white).rgb()) - ii.setDotsPerMeterX(dpi / 0.0254) # Convert inches to meters - ii.setDotsPerMeterY(dpi / 0.0254) - pp = QPainter(ii) - pp.setRenderHint(QPainter.Antialiasing) - pp.setRenderHint(QPainter.TextAntialiasing) - pp.setRenderHint(QPainter.SmoothPixmapTransform) - - scene.render(pp, targetRect, scene.sceneRect(), ratio_mode) - pp.end() - ii.save(imgName) - - return w/main_rect.width(), h/main_rect.height() diff --git a/ete2/treeview/main.pyc b/ete2/treeview/main.pyc deleted file mode 100644 index 9e166d1..0000000 Binary files a/ete2/treeview/main.pyc and /dev/null differ diff --git a/ete2/treeview/node_gui_actions.py b/ete2/treeview/node_gui_actions.py deleted file mode 100644 index da7f0fd..0000000 --- a/ete2/treeview/node_gui_actions.py +++ /dev/null @@ -1,172 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -from main import random_color -from PyQt4 import QtCore, QtGui - -class _NodeActions(object): - """ Used to extend QGraphicsItem features """ - def __init__(self): - self.setCursor(QtCore.Qt.PointingHandCursor) - self.setAcceptsHoverEvents(True) - - def mouseReleaseEvent(self, e): - if not self.node: - return - if e.button() == QtCore.Qt.RightButton: - self.showActionPopup() - elif e.button() == QtCore.Qt.LeftButton: - self.scene().view.set_focus(self.node) - #self.scene().view.prop_table.update_properties(self.node) - - - def hoverEnterEvent (self, e): - if self.node: - if self.node in self.scene().view.n2hl: - pass - else: - self.scene().view.highlight_node(self.node, fullRegion=True) - - def hoverLeaveEvent(self,e): - if self.node: - if self.node in self.scene().view.n2hl: - self.scene().view.unhighlight_node(self.node, reset=False) - - def mousePressEvent(self,e): - pass - - def mouseDoubleClickEvent(self,e): - if self.node: - item = self.scene().n2i[self.node] - if item.highlighted: - self.scene().view.unhighlight_node(self.node, reset=True) - else: - self.scene().view.highlight_node(self.node, fullRegion=True, - bg=random_color(l=0.5, s=0.5), permanent=True) - - def showActionPopup(self): - contextMenu = QtGui.QMenu() - if self.node.img_style["draw_descendants"] == False: - contextMenu.addAction( "Expand" , self.toggle_collapse) - else: - contextMenu.addAction( "Collapse" , self.toggle_collapse) - - contextMenu.addAction( "Set as outgroup" , self.set_as_outgroup) - contextMenu.addAction( "Swap branches" , self.swap_branches) - contextMenu.addAction( "Delete node" , self.delete_node) - contextMenu.addAction( "Delete partition" , self.detach_node) - contextMenu.addAction( "Add childs" , self.add_children) - contextMenu.addAction( "Populate partition" , self.populate_partition) - if self.node.up is not None and\ - self.scene().tree == self.node: - contextMenu.addAction( "Back to parent", self.back_to_parent_node) - else: - contextMenu.addAction( "Extract" , self.set_start_node) - - if self.scene().view.buffer_node: - contextMenu.addAction( "Paste partition" , self.paste_partition) - - contextMenu.addAction( "Cut partition" , self.cut_partition) - contextMenu.addAction( "Show newick" , self.show_newick) - contextMenu.exec_(QtGui.QCursor.pos()) - - def show_newick(self): - d = NewickDialog(self.node) - d._conf = _show_newick.Ui_Newick() - d._conf.setupUi(d) - d.update_newick() - d.exec_() - return False - - def delete_node(self): - self.node.delete() - self.scene().draw() - - def detach_node(self): - self.node.detach() - self.scene().draw() - - def swap_branches(self): - self.node.swap_children() - self.scene().draw() - - def add_children(self): - n,ok = QtGui.QInputDialog.getInteger(None,"Add childs","Number of childs to add:",1,1) - if ok: - for i in xrange(n): - ch = self.node.add_child() - self.scene().draw() - - def void(self): - return True - - def set_as_outgroup(self): - self.scene().tree.set_outgroup(self.node) - self.scene().draw() - - def toggle_collapse(self): - self.node.img_style["draw_descendants"] ^= True - self.scene().draw() - - def cut_partition(self): - self.scene().view.buffer_node = self.node - self.node.detach() - self.scene().draw() - - def paste_partition(self): - if self.scene().view.buffer_node: - self.node.add_child(self.scene().view.buffer_node) - self.scene().view.buffer_node= None - self.scene().draw() - - def populate_partition(self): - n, ok = QtGui.QInputDialog.getInteger(None,"Populate partition","Number of nodes to add:",2,1) - if ok: - self.node.populate(n) - #self.scene().set_style_from(self.scene().tree,self.scene().layout_func) - self.scene().draw() - - def set_start_node(self): - self.scene().start_node = self.node - self.scene().draw() - - def back_to_parent_node(self): - self.scene().start_node = self.node.up - self.scene().draw() diff --git a/ete2/treeview/node_gui_actions.pyc b/ete2/treeview/node_gui_actions.pyc deleted file mode 100644 index b37c68d..0000000 Binary files a/ete2/treeview/node_gui_actions.pyc and /dev/null differ diff --git a/ete2/treeview/qt4_circular_render.py b/ete2/treeview/qt4_circular_render.py deleted file mode 100644 index bf46ea1..0000000 --- a/ete2/treeview/qt4_circular_render.py +++ /dev/null @@ -1,403 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -import math -import colorsys -from PyQt4 import QtCore, QtGui -from main import _leaf, tracktime -from node_gui_actions import _NodeActions - - -class _LineItem(QtGui.QGraphicsLineItem): - def paint(self, painter, option, widget): - #painter.setClipRect( option.exposedRect ) - QtGui.QGraphicsLineItem.paint(self, painter, option, widget) - - -class ArcPartition(QtGui.QGraphicsPathItem): - def __init__(self, parent=None): - QtGui.QGraphicsPathItem.__init__(self, parent) - self.setCacheMode(QtGui.QGraphicsItem.DeviceCoordinateCache) - #self.setCacheMode(QtGui.QGraphicsItem.ItemCoordinateCache) - - def set_arc(self, cxdist, cydist, r1, r2, angle_start, angle_end): - """ Draws a 2D arc with two arc lines of length r1 (inner) and - r2 (outer) with center in cxdist,cydist. angle_start and - angle_end are relative to the starting rotation point equal 0 - degrees """ - - #self.data = [cxdist, cydist, r1, r2, angle_start, angle_end] - d1 = r1 * 2 - d2 = r2 * 2 - r1_xstart = -r1 - cxdist - r1_ystart = -r1 + cydist - r2_xstart = -r2 - cxdist - r2_ystart = -r2 + cydist - angle_start = angle_start - angle_end = angle_end - angle_span = angle_end + angle_start - - path = QtGui.QPainterPath() - # Calculate start and end points of inner arc - path.arcMoveTo(r1_xstart, r1_ystart, d1, d1, -angle_start) - i1 = path.currentPosition() - path.arcMoveTo(r1_xstart, r1_ystart, d1, d1, angle_end) - i2 = path.currentPosition() - # Moves to outer arc start position - path.arcMoveTo(r2_xstart, r2_ystart , d2, d2, -angle_start) - o1 = path.currentPosition() - # Draws outer arc - path.arcTo(r2_xstart, r2_ystart, d2, d2, -angle_start, angle_span) - o2 = path.currentPosition() - # Draws line to the end point in inner arc (straight line) - path.lineTo(i2) - # Draws inner arc from end point to to start - path.arcTo(r1_xstart, r1_ystart, d1, d1, angle_end, -angle_span) - # Draws line to the start point of outer arc (straight line) - path.lineTo(o1) - self.setPath(path) - - def paint(self, painter, option, index): - return QtGui.QGraphicsPathItem.paint(self, painter, option, index) - - -class _ArcItem(QtGui.QGraphicsPathItem): - def __init__(self): - QtGui.QGraphicsPathItem.__init__(self) - - def set_arc(self, cxdist, cydist, r1, r2, angle_start, angle_end): - """ Draws a 2D arc with two arc lines of length r1 (inner) and - r2 (outer) with center in cxdist,cydist. angle_start and - angle_end are relative to the starting rotation point equal 0 - degrees """ - - def clockwise(a): - if a<0: - return -1 * (a) - else: - return -a - return a - - #self.data = [cxdist, cydist, r1, r2, angle_start, angle_end] - d1 = r1 * 2 - d2 = r2 * 2 - r1_xstart = -r1 - cxdist - r1_ystart = -r1 + cydist - r2_xstart = -r2 - cxdist - r2_ystart = -r2 + cydist - - # ArcTo does not use clockwise angles - angle_start = clockwise(angle_start) - angle_end = clockwise(angle_end) - angle_span = angle_end - angle_start - - path = QtGui.QPainterPath() - # Calculate start and end points of inner arc - path.arcMoveTo(r1_xstart, r1_ystart, d1, d1, angle_start) - i1 = path.currentPosition() - path.arcMoveTo(r1_xstart, r1_ystart, d1, d1, angle_end) - i2 = path.currentPosition() - # Moves to outer arc start position - path.arcMoveTo(r2_xstart, r2_ystart , d2, d2, angle_start) - o1 = path.currentPosition() - # Draws outer arc - path.arcTo(r2_xstart, r2_ystart, d2, d2, angle_start, angle_span) - o2 = path.currentPosition() - # Draws line to the end point in inner arc (straight line) - path.lineTo(i2) - # Draws inner arc from end point to to start - path.arcTo(r1_xstart, r1_ystart, d1, d1, angle_end, -angle_span) - # Draws line to the start point of outer arc (straight line) - #path.lineTo(o1) - self.setPath(path) - - def paint(self, painter, option, index): - return QtGui.QGraphicsPathItem.paint(self, painter, option, index) - -def rotate_and_displace(item, rotation, height, offset): - """ Rotates an item of a given height over its own left most edis and moves - the item offset units in the rotated x axis """ - t = QtGui.QTransform() - t.rotate(rotation) - t.translate(0, - (height / 2)) - t.translate(offset, 0) - item.setTransform(t) - - -def get_min_radius(w, h, angle, xoffset): - """ returns the radius and X-displacement required to render a - rectangle (w,h) within and given angle (a).""" - - # converts to radians - angle = (angle * math.pi) / 180 - b = xoffset + w - a = h / 2 - off = 0 - if xoffset: - effective_angle = math.atan(a / xoffset) - if effective_angle > angle / 2 and angle / 2 < math.pi: - off = a / math.tan(angle / 2) - bb = off + w - #r = math.sqrt(a**2 + bb**2) - r = math.hypot(a, bb) - off = max (off, xoffset) - xoffset - else: - #r = math.sqrt(a**2 + b**2) - r = math.hypot(a, b) - else: - # It happens on root nodes - #r1 = math.sqrt(a**2 + b**2) - r1 = math.hypot(a, b) - #effective_angle = math.asin(a/r1) - #r2 = w / math.cos(effective_angle) - #print r1, r2 - r = r1#+r2 - - return r, off - -def render_circular(root_node, n2i, rot_step): - max_r = 0.0 - for node in root_node.traverse('preorder', is_leaf_fn=_leaf): - item = n2i[node] - w = sum(item.widths[1:5]) - h = item.effective_height - - parent_radius = n2i[node.up].radius if node.up else item.xoff - angle = rot_step if _leaf(node) else item.angle_span - - if hasattr(item, "radius"): - r = item.radius - xoffset = 0 - else: - r, xoffset = get_min_radius(w, h, angle, parent_radius + item.widths[0]) - item.radius = r - node.add_features(rad=item.radius) - - #if xoffset: # DEBUG ONLY. IF Scale is correct, this should not be printed - # print "Offset detected in node", xoffset - - rotate_and_displace(item.content, item.rotation, h, parent_radius) - - max_r = max(max_r, r) - - if not _leaf(node) and len(node.children) > 1: - first_c = n2i[node.children[0]] - last_c = n2i[node.children[-1]] - # Vertical arc Line - rot_end = n2i[node.children[-1]].rotation - rot_start = n2i[node.children[0]].rotation - rot_span = abs(rot_end - rot_start) - C = item.vt_line - C.setParentItem(item) - path = QtGui.QPainterPath() - # Counter clock wise - start = r - node.img_style["vt_line_width"]/2 - path.arcMoveTo(-start, -start, start * 2, start * 2, 360 - rot_start - rot_span) - path.arcTo(-start, -start, start * 2, start * 2, 360 - rot_start - rot_span, rot_span) - # Faces - C.setPath(path) - item.static_items.append(C) - - - if hasattr(item, "content"): - - # If applies, it sets the length of the extra branch length - if item.extra_branch_line: - xtra = item.extra_branch_line.line().dx() - if xtra > 0: - xtra = xoffset + xtra - else: - xtra = xoffset - item.extra_branch_line.setLine(item.branch_length, item.center,\ - item.branch_length + xtra , item.center) - item.nodeRegion.setWidth(item.nodeRegion.width()+xtra) - - # And moves elements - if xoffset: - for i in item.movable_items: - i.moveBy(xoffset, 0) - - - n2i[root_node].max_r = max_r - return max_r - -def init_circular_leaf_item(node, n2i, n2f, last_rotation, rot_step): - item = n2i[node] - item.rotation = last_rotation - item.full_start = last_rotation - (rot_step / 2) - item.full_end = last_rotation + (rot_step / 2) - item.angle_span = rot_step - #item.center = item.nodeRegion.height() / 2 - item.effective_height = get_effective_height(node, n2i, n2f) - item.center = item.effective_height/2 - #item.setParentItem(n2i[node.up]) - -def init_circular_node_item(node, n2i, n2f): - item = n2i[node] - if len(node.children) > 1: - first_c = n2i[node.children[0]] - last_c = n2i[node.children[-1]] - rot_start = first_c.rotation - rot_end = last_c.rotation - item.rotation = rot_start + ((rot_end - rot_start) / 2) - item.full_start = first_c.full_start - item.full_end = last_c.full_end - item.angle_span = item.full_end - item.full_start - else: - child = n2i[node.children[0]] - rot_start = child.full_start - rot_end = child.full_end - item.angle_span = child.angle_span - item.rotation = child.rotation - #item.rotation = rot_start + ((rot_end - rot_start) / 2) - item.full_start = child.full_start - item.full_end = child.full_end - - item.effective_height = get_effective_height(node, n2i, n2f) - item.center = item.effective_height/2 - -def get_effective_height(n, n2i, n2f): - """Returns the height needed to calculated the adjustment - of node to its available angle. - """ - down_h = n2f[n]["branch-bottom"].h - up_h = n2f[n]["branch-top"].h - - right_h = n2i[n].nodeRegion.height()/2 - up_h = max(right_h, up_h) - down_h = max(right_h, down_h) - - fullR = n2i[n].fullRegion - center = fullR.height()/2 - return max(up_h, down_h)*2 - -#@tracktime -def calculate_optimal_scale(root_node, n2i, rot_step, img): - """ Note: Seems to be fast. 0.5s from a tree of 10.000 leaves""" - - n2minradius = {} - n2sumdist = {} - n2sumwidth = {} - visited_nodes = [] - # Calcula la posicion minima de los elementos (con scale=0, es - # decir, sin tener en cuenta branch lengths. - for node in root_node.traverse('preorder', is_leaf_fn=_leaf): - visited_nodes.append(node) - ndist = node.dist if not img.force_topology else 1.0 - item = n2i[node] - # Uses size of all node parts, except branch length - w = sum(item.widths[1:5]) - h = item.effective_height - parent_radius = n2minradius.get(node.up, 0) - angle = rot_step if _leaf(node) else item.angle_span - - r, xoffset = get_min_radius(w, h, angle, parent_radius) - n2minradius[node] = r - n2sumdist[node] = n2sumdist.get(node.up, 0) + ndist - # versed sine: the little extra line needed to complete the - # radius. - #vs = r - (parent_radius + xoffset + w) - n2sumwidth[node] = n2sumwidth.get(node.up, 0) + sum(item.widths[2:5]) #+ vs - - root_opening = 0.0 - most_distant = max(n2sumdist.values()) - if most_distant == 0: return 0.0 - - best_scale = None - for node in visited_nodes: - item = n2i[node] - ndist = node.dist if not img.force_topology else 1.0 - if best_scale is None: - best_scale = (n2minradius[node] - n2sumwidth[node]) / ndist if ndist else 0.0 - else: - #Whats the expected radius of this node? - current_rad = n2sumdist[node] * best_scale + (n2sumwidth[node] + root_opening) - - # If still too small, it means we need to increase scale. - if current_rad < n2minradius[node]: - # This is a simplification of the real ecuacion needed - # to calculate the best scale. Given that I'm not - # taking into account the versed sine of each parent - # node, the equation is actually very simple. - if img.root_opening_factor: - best_scale = (n2minradius[node] - (n2sumwidth[node])) / (n2sumdist[node] + (most_distant * img.root_opening_factor)) - root_opening = most_distant * best_scale * img.root_opening_factor - else: - best_scale = (n2minradius[node] - (n2sumwidth[node]) + root_opening) / n2sumdist[node] - #print "OOps adjusting scale", ndist, best_scale, n2minradius[node], current_rad, item.heights[5], node.name - - # If the width of branch top/bottom faces is not covered, - # we can also increase the scale to adjust it. This may - # produce huge scales, so let's keep it optional - if img.optimal_scale_level == "full" and \ - item.widths[1] > ndist * best_scale: - best_scale = item.widths[1] / ndist - #print "OOps adjusting scale because branch-faces", ndist, best_scale, item.widths[1] - - # Adjust scale for aligned faces - if not img.allow_face_overlap: - aligned_h = [(n2i[node].heights[5], node) for node in visited_nodes] - aligned_h.sort(reverse=True) - maxh, maxh_node = aligned_h[0] - angle = n2i[maxh_node].angle_span - rad, off = get_min_radius(1, maxh, angle, 0.0001) - min_alg_scale = None - for node in visited_nodes: - if n2i[node].heights[5]: - new_scale = (rad - (n2sumwidth[node] + root_opening)) / n2sumdist[node] - min_alg_scale = min(new_scale, min_alg_scale) if min_alg_scale is not None else new_scale - if min_alg_scale > best_scale: - best_scale = min_alg_scale - - if root_opening: - n2i[root_node].nodeRegion.adjust(root_opening, 0, root_opening, 0) - n2i[root_node].fullRegion.adjust(root_opening, 0, root_opening, 0) - n2i[root_node].xoff = root_opening - #n2i[root_node].widths[0] += root_opening - - #for node in visited_nodes: - # item = n2i[node] - # h = item.effective_height - # a = n2sumdist[node] * best_scale + n2sumwidth.get(node) - # b = h/2 - # item.radius = math.sqrt(a**2 + b**2) - #print "root opening", root_opening - #best_scale = max(best_scale, min_scale) - return best_scale \ No newline at end of file diff --git a/ete2/treeview/qt4_circular_render.pyc b/ete2/treeview/qt4_circular_render.pyc deleted file mode 100644 index 392e085..0000000 Binary files a/ete2/treeview/qt4_circular_render.pyc and /dev/null differ diff --git a/ete2/treeview/qt4_face_render.py b/ete2/treeview/qt4_face_render.py deleted file mode 100644 index c450c2c..0000000 --- a/ete2/treeview/qt4_face_render.py +++ /dev/null @@ -1,386 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -import random -from PyQt4 import QtCore, QtGui -from PyQt4.QtGui import QGraphicsSimpleTextItem, QGraphicsPixmapItem, \ - QGraphicsRectItem, QTransform, QBrush, QPen, QColor, QGraphicsItem - -from main import FACE_POSITIONS, _leaf -from node_gui_actions import _NodeActions as _ActionDelegator -from math import pi, cos, sin - -class _TextFaceItem(QGraphicsSimpleTextItem, _ActionDelegator): - def __init__(self, face, node, text): - QGraphicsSimpleTextItem.__init__(self, text) - _ActionDelegator.__init__(self) - self.node = node - self.face = face - self._bounding_rect = self.face.get_bounding_rect() - self._real_rect = self.face.get_real_rect() - def boundingRect(self): - return self._bounding_rect - -class _ImgFaceItem(QGraphicsPixmapItem, _ActionDelegator): - def __init__(self, face, node, pixmap): - QGraphicsPixmapItem.__init__(self, pixmap) - _ActionDelegator.__init__(self) - self.node = node - -class _BackgroundFaceItem(QGraphicsRectItem): - def __init__(self, face, node): - QGraphicsRectItem.__init__(self) - self.node = node - - def paint(self, painter, option, index): - return - -class _FaceGroupItem(QGraphicsRectItem): # I was about to name this FaceBookItem :) - def paint(self, painter, option, index): - "Avoid little dots in acrobat reader" - return - - def __init__(self, faces, node, as_grid=False): - - # This caused seg. faults. in some computers. No idea why. - # QtGui.QGraphicsItem.__init__(self, *args, **kargs) - QGraphicsRectItem.__init__(self, 0, 0, 0, 0) - - self.as_grid = as_grid - self.c2max_w = {} - self.r2max_h = {} - self.node = node - self.column2faces = faces - self.column2size = {} - self.columns = sorted(set(self.column2faces.keys())) - - # Two dictionaries containing min column size. Can be used to - # reserve some space to specific columns and draw FaceBlocks - # like tables. - self.column_widths = {} - self.row_heights = {} - - self.w = 0 - self.h = 0 - # updates the size of this grid - self.update_columns_size() - - def set_min_column_widths(self, column_widths): - # column_widths is a dictionary of min column size. Can be - # used to reserve horizontal space to specific columns - self.column_widths = column_widths - self.columns = sorted(set(self.column2faces.keys() + self.column_widths.keys())) - - def set_min_column_heights(self, column_heights): - # column_widths is a dictionary of min column size. Can be - # used to reserve vertical space to specific columns - self.row_heights = column_heights - - #def paint(self, painter, option, index): - # return - - def boundingRect(self): - return QtCore.QRectF(0,0, self.w, self.h) - - def rect(self): - return QtCore.QRectF(0,0, self.w, self.h) - - def get_size(self): - return self.w, self.h - - def update_columns_size(self): - self.sizes = {} - self.c2height = {} - - for c, faces in self.column2faces.iteritems(): - self.sizes[c] = {} - total_height = 0 - for r, f in enumerate(faces): - f.node = self.node - if f.type == "pixmap": - f.update_pixmap() - elif f.type == "item": - f.update_items() - elif f.type == "text" and f.rotation: - f.tight_text = False - - width = f._width() + f.margin_right + f.margin_left - height = f._height() + f.margin_top + f.margin_bottom - - if f.rotation: - if f.rotation == 90 or f.rotation == 270: - width, height = height, width - elif f.rotation == 180: - pass - else: - x0 = width/2.0 - y0 = height/2.0 - theta = (f.rotation * pi)/180 - trans = lambda x, y: (x0+(x-x0)*cos(theta) + (y-y0)*sin(theta), y0-(x-x0)*sin(theta)+(y-y0)*cos(theta)) - coords = (trans(0,0), trans(0,height), trans(width,0), trans(width,height)) - x_coords = [e[0] for e in coords] - y_coords = [e[1] for e in coords] - width = max(x_coords) - min(x_coords) - height = max(y_coords) - min(y_coords) - - self.sizes[c][r] = [width, height] - self.c2max_w[c] = max(self.c2max_w.get(c, 0), width) - self.r2max_h[r] = max(self.r2max_h.get(r, 0), height) - total_height += height - self.c2height[c] = total_height - - if not self.sizes: - return - - if self.as_grid: - self.h = max( [sum([self.r2max_h[r] for r in rows.iterkeys()]) for c, rows in self.sizes.iteritems()]) - else: - self.h = max( [self.c2height[c] for c in self.sizes.iterkeys()]) - - self.w = sum(self.c2max_w.values()) - #self.setRect(0, 0, self.w+random.randint(1,5), self.h) - #pen = QtGui.QPen() - #pen.setColor(QtGui.QColor("red")) - #self.setPen(pen) - - def setup_grid(self, c2max_w=None, r2max_h=None, as_grid=True): - if c2max_w: - self.c2max_w = c2max_w - - if r2max_h: - self.r2max_h = r2max_h - - self.as_grid = as_grid - self.update_columns_size() - return self.c2max_w, self.r2max_h - - - def render(self): - x = 0 - for c in self.columns: - max_w = self.c2max_w[c] - faces = self.column2faces.get(c, []) - - if self.as_grid: - y = 0 - else: - y = (self.h - self.c2height.get(c,0)) / 2 - - for r, f in enumerate(faces): - w, h = self.sizes[c][r] - if self.as_grid: - max_h = self.r2max_h[r] - else: - max_h = h - - f.node = self.node - if f.type == "text": - obj = _TextFaceItem(f, self.node, f.get_text()) - font = f._get_font() - obj.setFont(font) - obj.setBrush(QBrush(QColor(f.fgcolor))) - elif f.type == "item": - obj = f.item - else: - # Loads the pre-generated pixmap - obj = _ImgFaceItem(f, self.node, f.pixmap) - - obj.setAcceptsHoverEvents(True) - obj.setParentItem(self) - - x_offset, y_offset = 0, 0 - - if max_w > w: - # Horizontally at the left - if f.hz_align == 0: - x_offset = 0 - elif f.hz_align == 1: - # Horizontally centered - x_offset = (max_w - w) / 2 - elif f.hz_align == 2: - # At the right - x_offset = (max_w - w) - - if max_h > h: - if f.vt_align == 0: - # Vertically on top - y_offset = 0 - elif f.vt_align == 1: - # Vertically centered - y_offset = (max_h - h) / 2 - elif f.hz_align == 2: - # Vertically at bottom - y_offset = (max_h - h) - - # Correct cases in which object faces has negative - # starting points - #obj_rect = obj.boundingRect() - #_pos = obj_rect.topLeft() - #_x = abs(_pos.x()) if _pos.x() < 0 else 0 - #_y = abs(_pos.y()) if _pos.y() < 0 else 0 - - text_y_offset = -obj.boundingRect().y() if f.type == "text" else 0 - - obj.setPos(x + f.margin_left + x_offset, - y + y_offset + f.margin_top + text_y_offset) - - if f.rotation and f.rotation != 180: - fake_rect = obj.boundingRect() - fake_w, fake_h = fake_rect.width(), fake_rect.height() - self._rotate_item(obj, f.rotation) - #wcorr = fake_w/2.0 - w/2.0 - #ycorr = fake_h/2.0 - h/2.0 - #print "Correctopm", fake_w/2.0 - w/2.0, fake_h/2.0 - h/2 - #obj.moveBy(-wcorr, -ycorr) - obj.moveBy(((w/2) - fake_w/2.0), (h/2) - (fake_h/2.0)) - #r = QGraphicsRectItem(0, 0, w, h) - #r.setParentItem(self) - - obj.rotable = f.rotable - f.inner_background.apply(obj) - f.inner_border.apply(obj) - - bg = f.background.apply(obj) - border = f.border.apply(obj) - #if border: - # border.setRect(x, y, max_w, max_h) - # border.setParentItem(self) - if bg: - bg.setRect(x, y, max_w, max_h) - bg.setParentItem(self) - - if f.opacity < 1: - obj.setOpacity(f.opacity) - - if self.as_grid: - y += max_h - else: - y += h - - x += max_w - - def _rotate_item(self, item, rotation): - if hasattr(item, "_real_rect"): - rect = item._real_rect - else: - rect = item.boundingRect() - x = rect.width()/2 - y = rect.height()/2 - matrix = item.transform() - #item.setTransform(QTransform().translate(x, y).rotate(rotation).translate(-x, -y)) - item.setTransform(matrix.translate(x, y).rotate(rotation).translate(-x, -y)) - - def rotate(self, rotation): - "rotates item over its own center" - for obj in self.childItems(): - if hasattr(obj, "rotable") and obj.rotable: - if hasattr(obj, "_real_rect"): - # to avoid incorrect rotation of tightgly wrapped - # text items we need to rotate using the real - # wrapping rect and revert y_text correction. - yoff = obj.boundingRect().y() - rect = obj._real_rect - # OJO!! this only works for the rotation of text - # faces in circular mode. Other cases are - # unexplored!! - obj.moveBy(0, yoff*2) - else: - yoff = None - rect = obj.boundingRect() - x = rect.width() / 2 - y = rect.height() / 2 - matrix = obj.transform() - #obj.setTransform(QTransform().translate(x, y).rotate(rotation).translate(-x, -y)) - obj.setTransform(matrix.translate(x, y).rotate(rotation).translate(-x, -y)) - - def flip_hz(self): - for obj in self.childItems(): - rect = obj.boundingRect() - x = rect.width() / 2 - y = rect.height() / 2 - matrix = obj.transform() - #obj.setTransform(QTransform().translate(x, y).scale(-1,1).translate(-x, -y)) - obj.setTransform(matrix.translate(x, y).scale(-1,1).translate(-x, -y)) - - def flip_vt(self): - for obj in self.childItems(): - rect = obj.boundingRect() - x = rect.width() / 2 - y = rect.height() / 2 - matrix = obj.transform() - #obj.setTransform(QTransform().translate(x, y).scale(1,-1).translate(-x, -y)) - obj.setTransform(matrix.translate(x, y).scale(1,-1).translate(-x, -y)) - - - -def update_node_faces(node, n2f, img): - - # Organize all faces of this node in FaceGroups objects - # (tables of faces) - faceblock = {} - - n2f[node] = faceblock - for position in FACE_POSITIONS: - # _temp_faces.position = - # 1: [f1, f2, f3], - # 2: [f4, f4], - # ... - - # In case there are fixed faces - fixed_faces = getattr(getattr(node, "faces", None) , position, {}) - - # _temp_faces should be initialized by the set_style funcion - all_faces = getattr(node._temp_faces, position) - for column, values in fixed_faces.iteritems(): - all_faces.setdefault(column, []).extend(values) - - if position == "aligned" and img.draw_aligned_faces_as_table: - as_grid = False - else: - as_grid = False - - faceblock[position] = _FaceGroupItem(all_faces, node, as_grid=as_grid) - - # all temp and fixed faces are now referenced by the faceblock, so - # we can clear the node temp faces (don't want temp faces to be - # replicated with copy or dumped with cpickle) - node._temp_faces = None - - return faceblock diff --git a/ete2/treeview/qt4_face_render.pyc b/ete2/treeview/qt4_face_render.pyc deleted file mode 100644 index 84c1f7b..0000000 Binary files a/ete2/treeview/qt4_face_render.pyc and /dev/null differ diff --git a/ete2/treeview/qt4_gui.py b/ete2/treeview/qt4_gui.py deleted file mode 100644 index 03f2a60..0000000 --- a/ete2/treeview/qt4_gui.py +++ /dev/null @@ -1,908 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -import re -from sys import stderr -from PyQt4 import QtCore, QtGui -from PyQt4.QtGui import QBrush, QPen, QGraphicsRectItem -from PyQt4.QtGui import QPrinter -from PyQt4.QtCore import QThread, SIGNAL -try: - from PyQt4 import QtOpenGL - USE_GL = True - USE_GL = False # Temporarily disabled -except ImportError: - USE_GL = False - -import _mainwindow, _search_dialog, _show_newick, _open_newick, _about -from main import TreeStyle, save, random_color -from qt4_render import render -from ete2._ph import new_version -from ete2 import Tree, TreeStyle -import time - -class _SelectorItem(QtGui.QGraphicsRectItem): - def __init__(self, parent=None): - self.Color = QtGui.QColor("blue") - self._active = False - QtGui.QGraphicsRectItem.__init__(self, 0, 0, 0, 0, parent=parent) - - def paint(self, p, option, widget): - p.setPen(self.Color) - p.setBrush(QtGui.QBrush(QtCore.Qt.NoBrush)) - p.drawRect(self.rect().x(),self.rect().y(),self.rect().width(),self.rect().height()) - return - # Draw info text - font = QtGui.QFont("Arial",13) - text = "%d selected." % len(self.get_selected_nodes()) - textR = QtGui.QFontMetrics(font).boundingRect(text) - if self.rect().width() > textR.width() and \ - self.rect().height() > textR.height()/2 and 0: # OJO !!!! - p.setPen(QtGui.QPen(self.Color)) - p.setFont(QtGui.QFont("Arial",13)) - p.drawText(self.rect().bottomLeft().x(),self.rect().bottomLeft().y(),text) - - def get_selected_nodes(self): - selPath = QtGui.QPainterPath() - selPath.addRect(self.rect()) - self.scene().setSelectionArea(selPath) - return [i.node for i in self.scene().selectedItems()] - - def setActive(self,bool): - self._active = bool - - def isActive(self): - return self._active - -def etime(f): - def a_wrapper_accepting_arguments(*args, **kargs): - global TIME - t1 = time.time() - f(*args, **kargs) - print time.time() - t1 - return a_wrapper_accepting_arguments - -class CheckUpdates(QThread): - def run(self): - try: - current, latest, tag = new_version() - if tag is None: - tag = "" - msg = "" - if current and latest: - if current < latest: - msg = "New version available (rev%s): %s More info at http://ete.cgenomics.org." %\ - (latest, tag) - elif current == latest: - msg = "Up to date" - self.emit(SIGNAL("output(QString)"), msg) - except Exception: - pass - -class _GUI(QtGui.QMainWindow): - def _updatestatus(self, msg): - self.main.statusbar.showMessage(msg) - - def redraw(self): - self.scene.draw() - self.view.init_values() - - def __init__(self, scene, *args): - QtGui.QMainWindow.__init__(self, *args) - self.main = _mainwindow.Ui_MainWindow() - self.main.setupUi(self) - self.setWindowTitle("ETE Tree Browser") - - self.scene = scene - self.view = _TreeView(scene) - scene.view = self.view - self.node_properties = _PropertiesDialog(scene) - self.view.prop_table = self.node_properties - - self.view.centerOn(0,0) - if scene.img.show_branch_length: - self.main.actionBranchLength.setChecked(True) - if scene.img.show_branch_support: - self.main.actionBranchSupport.setChecked(True) - if scene.img.show_leaf_name: - self.main.actionLeafName.setChecked(True) - if scene.img.force_topology: - self.main.actionForceTopology.setChecked(True) - - splitter = QtGui.QSplitter() - splitter.addWidget(self.view) - splitter.addWidget(self.node_properties) - self.setCentralWidget(splitter) - # I create a single dialog to keep the last search options - self.searchDialog = QtGui.QDialog() - # Don't know if this is the best way to set up the dialog and - # its variables - self.searchDialog._conf = _search_dialog.Ui_Dialog() - self.searchDialog._conf.setupUi(self.searchDialog) - - self.scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex) - - # Shows the whole tree by default - self.view.fitInView(self.scene.sceneRect(), QtCore.Qt.KeepAspectRatio) - - # Check for updates - self.check = CheckUpdates() - #self.check.start() - #self.connect(self.check, SIGNAL("output(QString)"), self._updatestatus) - - @QtCore.pyqtSignature("") - def on_actionETE_triggered(self): - try: - __VERSION__ - except: - __VERSION__= "development branch" - - d = QtGui.QDialog() - d._conf = _about.Ui_About() - d._conf.setupUi(d) - d._conf.version.setText("Version: %s" %__VERSION__) - d._conf.version.setAlignment(QtCore.Qt.AlignHCenter) - d.exec_() - - @QtCore.pyqtSignature("") - def on_actionZoomOut_triggered(self): - self.view.safe_scale(0.8,0.8) - - @QtCore.pyqtSignature("") - def on_actionZoomIn_triggered(self): - self.view.safe_scale(1.2,1.2) - - @QtCore.pyqtSignature("") - def on_actionZoomInX_triggered(self): - self.scene.img._scale += self.scene.img._scale * 0.05 - self.redraw() - - @QtCore.pyqtSignature("") - def on_actionZoomOutX_triggered(self): - self.scene.img._scale -= self.scene.img._scale * 0.05 - self.redraw() - - @QtCore.pyqtSignature("") - def on_actionZoomInY_triggered(self): - self.scene.img.branch_vertical_margin += 5 - self.scene.img._scale = None - self.redraw() - - @QtCore.pyqtSignature("") - def on_actionZoomOutY_triggered(self): - if self.scene.img.branch_vertical_margin > 0: - margin = self.scene.img.branch_vertical_margin - 5 - if margin > 0: - self.scene.img.branch_vertical_margin = margin - else: - self.scene.img.branch_vertical_margin = 0.0 - self.scene.img._scale = None - self.redraw() - - @QtCore.pyqtSignature("") - def on_actionFit2tree_triggered(self): - self.view.fitInView(self.scene.sceneRect(), QtCore.Qt.KeepAspectRatio) - - @QtCore.pyqtSignature("") - def on_actionFit2region_triggered(self): - R = self.view.selector.rect() - if R.width()>0 and R.height()>0: - self.view.fitInView(R.x(), R.y(), R.width(),\ - R.height(), QtCore.Qt.KeepAspectRatio) - - @QtCore.pyqtSignature("") - def on_actionSearchNode_triggered(self): - setup = self.searchDialog._conf - setup.attrValue.setFocus() - ok = self.searchDialog.exec_() - if ok: - mType = setup.attrType.currentIndex() - aName = str(setup.attrName.text()) - if mType >= 2 and mType <=6: - try: - aValue = float(setup.attrValue.text()) - except ValueError: - QtGui.QMessageBox.information(self, "!",\ - "A numeric value is expected") - return - elif mType == 7: - aValue = re.compile(str(setup.attrValue.text())) - elif mType == 0 or mType == 1: - aValue = str(setup.attrValue.text()) - - if mType == 1 or mType == 2: #"is or ==" - cmpFn = lambda x,y: x == y - elif mType == 0: # "contains" - cmpFn = lambda x,y: y in x - elif mType == 3: - cmpFn = lambda x,y: x >= y - elif mType == 4: - cmpFn = lambda x,y: x > y - elif mType == 5: - cmpFn = lambda x,y: x <= y - elif mType == 6: - cmpFn = lambda x,y: x < y - elif mType == 7: - cmpFn = lambda x,y: re.search(y, x) - - for n in self.scene.tree.traverse(is_leaf_fn=_leaf): - if setup.leaves_only.isChecked() and not _leaf(n): - continue - if hasattr(n, aName) \ - and cmpFn(getattr(n, aName), aValue ): - self.scene.view.highlight_node(n) - - @QtCore.pyqtSignature("") - def on_actionClear_search_triggered(self): - # This could be much more efficient - for n in self.view.n2hl.keys(): - self.scene.view.unhighlight_node(n) - - @QtCore.pyqtSignature("") - def on_actionBranchLength_triggered(self): - self.scene.img.show_branch_length ^= True - self.scene.img._scale = None - self.redraw() - self.view.centerOn(0,0) - - @QtCore.pyqtSignature("") - def on_actionBranchSupport_triggered(self): - self.scene.img.show_branch_support ^= True - self.scene.img._scale = None - self.redraw() - self.view.centerOn(0,0) - - @QtCore.pyqtSignature("") - def on_actionLeafName_triggered(self): - self.scene.img.show_leaf_name ^= True - self.scene.img._scale = None - self.redraw() - self.view.centerOn(0,0) - - @QtCore.pyqtSignature("") - def on_actionForceTopology_triggered(self): - self.scene.img.force_topology ^= True - self.scene.img._scale = None - self.redraw() - self.view.centerOn(0,0) - - @QtCore.pyqtSignature("") - def on_actionShow_newick_triggered(self): - d = NewickDialog(self.scene.tree) - d._conf = _show_newick.Ui_Newick() - d._conf.setupUi(d) - d.update_newick() - d.exec_() - - @QtCore.pyqtSignature("") - def on_actionChange_orientation_triggered(self): - self.scene.props.orientation ^= 1 - self.redraw() - - @QtCore.pyqtSignature("") - def on_actionShow_phenogram_triggered(self): - self.scene.props.style = 0 - self.redraw() - - @QtCore.pyqtSignature("") - def on_actionShowCladogram_triggered(self): - self.scene.props.style = 1 - self.redraw() - - @QtCore.pyqtSignature("") - def on_actionOpen_triggered(self): - d = QtGui.QFileDialog() - d._conf = _open_newick.Ui_OpenNewick() - d._conf.setupUi(d) - d.exec_() - return - fname = QtGui.QFileDialog.getOpenFileName(self ,"Open File", - "/home", - ) - try: - t = Tree(str(fname)) - except Exception, e: - print e - else: - self.scene.tree = t - self.img = TreeStyle() - self.redraw() - - @QtCore.pyqtSignature("") - def on_actionSave_newick_triggered(self): - fname = QtGui.QFileDialog.getSaveFileName(self ,"Save File", - "/home", - "Newick (*.nh *.nhx *.nw )") - nw = self.scene.tree.write() - try: - OUT = open(fname,"w") - except Exception, e: - print e - else: - OUT.write(nw) - OUT.close() - - @QtCore.pyqtSignature("") - def on_actionRenderPDF_triggered(self): - F = QtGui.QFileDialog(self) - if F.exec_(): - imgName = str(F.selectedFiles()[0]) - if not imgName.endswith(".pdf"): - imgName += ".pdf" - save(self.scene, imgName) - - - @QtCore.pyqtSignature("") - def on_actionRender_selected_region_triggered(self): - if not self.scene.selector.isVisible(): - return QtGui.QMessageBox.information(self, "!",\ - "You must select a region first") - - F = QtGui.QFileDialog(self) - if F.exec_(): - imgName = str(F.selectedFiles()[0]) - if not imgName.endswith(".pdf"): - imgName += ".pdf" - save(imgName, take_region=True) - - - @QtCore.pyqtSignature("") - def on_actionPaste_newick_triggered(self): - text,ok = QtGui.QInputDialog.getText(self,\ - "Paste Newick",\ - "Newick:") - if ok: - try: - t = Tree(str(text)) - except Exception,e: - print e - else: - self.scene.tree = t - self.redraw() - self.view.centerOn(0,0) - - def keyPressEvent(self,e): - key = e.key() - control = e.modifiers() & QtCore.Qt.ControlModifier - if key == 77: - if self.isMaximized(): - self.showNormal() - else: - self.showMaximized() - elif key >= 49 and key <= 58: - key = key - 48 - m = self.view.matrix() - m.reset() - self.view.setMatrix(m) - self.view.scale(key, key) - - -# This function should be reviewed. Probably there are better ways to -# do de same, or at least less messy ways... So far this is what I -# have -class _TableItem(QtGui.QItemDelegate): - def __init__(self, parent=None): - QtGui.QItemDelegate.__init__(self, parent) - self.propdialog = parent - - def paint(self, painter, style, index): - self.propdialog.tableView.setRowHeight(index.row(), 18) - val = index.data() - if getattr(val, "background", None): - painter.fillRect(style.rect, QtGui.QColor(val.background)) - QtGui.QItemDelegate.paint(self, painter, style, index) - - def createEditor(self, parent, option, index): - # Edit only values, not property names - if index.column() != 1: - return None - - originalValue = index.model().data(index) - if not self.isSupportedType(originalValue.type()): - return None - - if re.search("^#[0-9ABCDEFabcdef]{6}$",str(originalValue.toString())): - origc = QtGui.QColor(str(originalValue.toString())) - color = QtGui.QColorDialog.getColor(origc) - if color.isValid(): - self.propdialog._edited_indexes.add( (index.row(), index.column()) ) - index.model().setData(index,QtCore.QVariant(color.name())) - self.propdialog.apply_changes() - - return None - else: - editField = QtGui.QLineEdit(parent) - editField.setFrame(False) - validator = QtGui.QRegExpValidator(QtCore.QRegExp(".+"), editField) - editField.setValidator(validator) - self.connect(editField, QtCore.SIGNAL("returnPressed()"), - self.commitAndCloseEditor) - self.connect(editField, QtCore.SIGNAL("returnPressed()"), - self.propdialog.apply_changes) - self.propdialog._edited_indexes.add( (index.row(), index.column()) ) - return editField - - def setEditorData(self, editor, index): - value = index.model().data(index) - if editor is not None: - editor.setText(self.displayText(value)) - - def isSupportedType(valueType): - return True - - isSupportedType = staticmethod(isSupportedType) - def displayText(self,value): - return value.toString() - - def commitAndCloseEditor(self): - editor = self.sender() - self.emit(QtCore.SIGNAL("commitData(QWidget *)"), editor) - self.emit(QtCore.SIGNAL("closeEditor(QWidget *)"), editor) - -class _PropModeChooser(QtGui.QWidget): - def __init__(self,scene, *args): - QtGui.QWidget.__init__(self,*args) - -class _PropertiesDialog(QtGui.QWidget): - def __init__(self, scene, *args): - QtGui.QWidget.__init__(self,*args) - self.scene = scene - self._mode = 0 - self.layout = QtGui.QVBoxLayout() - self.tableView = QtGui.QTableView() - self.tableView.verticalHeader().setVisible(False) - #self.tableView.horizontalHeader().setVisible(True) - #self.tableView.setVerticalHeader(None) - self.layout.addWidget(self.tableView) - self.setLayout(self.layout) - self.tableView.setGeometry (0, 0, 200,200) - - - def update_properties(self, node): - self.node = node - self._edited_indexes = set([]) - self._style_indexes = set([]) - self._prop_indexes = set([]) - - self.get_prop_table(node) - - def get_props_in_nodes(self, nodes): - # sorts properties and faces of selected nodes - self.prop2nodes = {} - self.prop2values = {} - self.style2nodes = {} - self.style2values = {} - - for n in nodes: - for pname in n.features: - pvalue = getattr(n,pname) - if type(pvalue) == int or \ - type(pvalue) == float or \ - type(pvalue) == str : - self.prop2nodes.setdefault(pname,[]).append(n) - self.prop2values.setdefault(pname,[]).append(pvalue) - - for pname,pvalue in n.img_style.iteritems(): - if type(pvalue) == int or \ - type(pvalue) == float or \ - type(pvalue) == str : - self.style2nodes.setdefault(pname,[]).append(n) - self.style2values.setdefault(pname,[]).append(pvalue) - - def get_prop_table(self, node): - if self._mode == 0: # node - self.get_props_in_nodes([node]) - elif self._mode == 1: # childs - self.get_props_in_nodes(node.get_leaves()) - elif self._mode == 2: # partition - self.get_props_in_nodes([node]+node.get_descendants()) - - total_props = len(self.prop2nodes) + len(self.style2nodes.keys()) - self.model = QtGui.QStandardItemModel(total_props, 2) - self.model.setHeaderData(0, QtCore.Qt.Horizontal, "Feature") - self.model.setHeaderData(1, QtCore.Qt.Horizontal, "Value") - self.tableView.setModel(self.model) - self.delegate = _TableItem(self) - self.tableView.setItemDelegate(self.delegate) - - row = 0 - items = self.prop2nodes.items() - for name, nodes in sorted(items): - value= getattr(nodes[0],name) - - index1 = self.model.index(row, 0, QtCore.QModelIndex()) - index2 = self.model.index(row, 1, QtCore.QModelIndex()) - f = QtCore.QVariant(name) - v = QtCore.QVariant(value) - self.model.setData(index1, f) - self.model.setData(index2, v) - self._prop_indexes.add( (index1, index2) ) - row +=1 - - keys = self.style2nodes.keys() - for name in sorted(keys): - value= self.style2values[name][0] - index1 = self.model.index(row, 0, QtCore.QModelIndex()) - index2 = self.model.index(row, 1, QtCore.QModelIndex()) - - self.model.setData(index1, QtCore.QVariant(name)) - v = QtCore.QVariant(value) - self.model.setData(index2, v) - # Creates a variant element - self._style_indexes.add( (index1, index2) ) - row +=1 - return - - def apply_changes(self): - # Apply changes on styles - for i1, i2 in self._style_indexes: - if (i2.row(), i2.column()) not in self._edited_indexes: - continue - name = str(self.model.data(i1).toString()) - value = str(self.model.data(i2).toString()) - for n in self.style2nodes[name]: - typedvalue = type(n.img_style[name])(value) - try: - n.img_style[name] = typedvalue - except: - #logger(-1, "Wrong format for attribute:", name) - break - - # Apply changes on properties - for i1, i2 in self._prop_indexes: - if (i2.row(), i2.column()) not in self._edited_indexes: - continue - name = str(self.model.data(i1).toString()) - value = str(self.model.data(i2).toString()) - for n in self.prop2nodes[name]: - try: - setattr(n, name, type(getattr(n,name))(value)) - except Exception, e: - #logger(-1, "Wrong format for attribute:", name) - print e - break - self.update_properties(self.node) - self.scene.img._scale = None - self.redraw() - return - -class NewickDialog(QtGui.QDialog): - def __init__(self, node, *args): - QtGui.QDialog.__init__(self, *args) - self.node = node - - def update_newick(self): - f= int(self._conf.nwFormat.currentText()) - self._conf.features_list.selectAll() - if self._conf.useAllFeatures.isChecked(): - features = [] - elif self._conf.features_list.count()==0: - features = None - else: - features = set() - for i in self._conf.features_list.selectedItems(): - features.add(str(i.text())) - - nw = self.node.write(format=f, features=features) - self._conf.newickBox.setText(nw) - - def add_feature(self): - aName = str(self._conf.attrName.text()).strip() - if aName != '': - self._conf.features_list.addItem(aName) - self.update_newick() - def del_feature(self): - r = self._conf.features_list.currentRow() - self._conf.features_list.takeItem(r) - self.update_newick() - - def set_custom_features(self): - state = self._conf.useAllFeatures.isChecked() - self._conf.features_list.setDisabled(state) - self._conf.attrName.setDisabled(state) - self.update_newick() - -class _TreeView(QtGui.QGraphicsView): - def __init__(self,*args): - QtGui.QGraphicsView.__init__(self,*args) - self.init_values() - - if USE_GL: - print "USING GL" - F = QtOpenGL.QGLFormat() - F.setSampleBuffers(True) - print F.sampleBuffers() - self.setViewport(QtOpenGL.QGLWidget(F)) - self.setRenderHints(QtGui.QPainter.Antialiasing) - else: - self.setRenderHints(QtGui.QPainter.Antialiasing or QtGui.QPainter.SmoothPixmapTransform ) - - self.setViewportUpdateMode(QtGui.QGraphicsView.BoundingRectViewportUpdate) - self.setRenderHints(QtGui.QPainter.Antialiasing or QtGui.QPainter.SmoothPixmapTransform ) - #self.setViewportUpdateMode(QtGui.QGraphicsView.NoViewportUpdate) - self.setCacheMode(QtGui.QGraphicsView.CacheBackground) - self.setResizeAnchor(QtGui.QGraphicsView.AnchorUnderMouse) - #self.setOptimizationFlag (QtGui.QGraphicsView.DontAdjustForAntialiasing) - self.setOptimizationFlag (QtGui.QGraphicsView.DontSavePainterState) - #self.setOptimizationFlag (QtGui.QGraphicsView.DontClipPainter) - #self.scene().setItemIndexMethod(QtGui.QGraphicsScene.NoIndex) - #self.scene().setBspTreeDepth(24) - - def init_values(self): - master_item = self.scene().master_item - self.n2hl = {} - self.focus_highlight = QtGui.QGraphicsRectItem(master_item) - self.buffer_node = None - self.focus_node = None - self.selector = _SelectorItem(master_item) - - def resizeEvent(self, e): - QtGui.QGraphicsView.resizeEvent(self, e) - - def safe_scale(self, xfactor, yfactor): - self.setTransformationAnchor(self.AnchorUnderMouse) - - xscale = self.matrix().m11() - yscale = self.matrix().m22() - srect = self.sceneRect() - - if (xfactor>1 and xscale>200000) or \ - (yfactor>1 and yscale>200000): - QtGui.QMessageBox.information(self, "!",\ - "I will take the microscope!") - return - - # Do not allow to reduce scale to a value producing height or with smaller than 20 pixels - # No restrictions to zoom in - if (yfactor<1 and srect.width() * yscale < 20): - pass - elif (xfactor<1 and srect.width() * xscale < 20): - pass - else: - self.scale(xfactor, yfactor) - - def highlight_node(self, n, fullRegion=False, fg="red", bg="gray", permanent=False): - self.unhighlight_node(n) - item = self.scene().n2i[n] - hl = QtGui.QGraphicsRectItem(item.content) - if fullRegion: - hl.setRect(item.fullRegion) - else: - hl.setRect(item.nodeRegion) - hl.setPen(QtGui.QColor(fg)) - hl.setBrush(QtGui.QColor(bg)) - hl.setOpacity(0.2) - # save info in Scene - self.n2hl[n] = hl - if permanent: - item.highlighted = True - - def unhighlight_node(self, n, reset=False): - if n in self.n2hl: - item = self.scene().n2i[n] - if not item.highlighted: - self.scene().removeItem(self.n2hl[n]) - del self.n2hl[n] - elif reset: - self.scene().removeItem(self.n2hl[n]) - del self.n2hl[n] - item.highlighted = False - else: - pass - - def wheelEvent(self,e): - factor = (-e.delta() / 360.0) - if abs(factor)>=1: - factor = 0.0 - - # Ctrl+Shift -> Zoom in X - if (e.modifiers() & QtCore.Qt.ControlModifier) and (e.modifiers() & QtCore.Qt.ShiftModifier): - self.safe_scale(1+factor, 1) - - # Ctrl+Alt -> Zomm in Y - elif (e.modifiers() & QtCore.Qt.ControlModifier) and (e.modifiers() & QtCore.Qt.AltModifier): - self.safe_scale(1,1+factor) - - # Ctrl -> Zoom X,Y - elif e.modifiers() & QtCore.Qt.ControlModifier: - self.safe_scale(1-factor, 1-factor) - - # Shift -> Horizontal scroll - elif e.modifiers() & QtCore.Qt.ShiftModifier: - if e.delta()>0: - self.horizontalScrollBar().setValue(self.horizontalScrollBar().value()-20 ) - else: - self.horizontalScrollBar().setValue(self.horizontalScrollBar().value()+20 ) - # No modifiers -> Vertival scroll - else: - if e.delta()>0: - self.verticalScrollBar().setValue(self.verticalScrollBar().value()-20 ) - else: - self.verticalScrollBar().setValue(self.verticalScrollBar().value()+20 ) - - def set_focus(self, node): - i = self.scene().n2i[node] - self.focus_highlight.setPen(QtGui.QColor("red")) - self.focus_highlight.setBrush(QtGui.QColor("SteelBlue")) - self.focus_highlight.setOpacity(0.2) - self.focus_highlight.setParentItem(i.content) - self.focus_highlight.setRect(i.fullRegion) - self.focus_highlight.setVisible(True) - self.prop_table.update_properties(node) - #self.focus_highlight.setRect(i.nodeRegion) - self.focus_node = node - self.update() - - def hide_focus(self): - return - #self.focus_highlight.setVisible(False) - - def keyPressEvent(self,e): - key = e.key() - control = e.modifiers() & QtCore.Qt.ControlModifier - #print >>sys.stderr, "****** Pressed key: ", key, QtCore.Qt.LeftArrow - if control: - if key == QtCore.Qt.Key_Left: - self.horizontalScrollBar().setValue(self.horizontalScrollBar().value()-20 ) - self.update() - elif key == QtCore.Qt.Key_Right: - self.horizontalScrollBar().setValue(self.horizontalScrollBar().value()+20 ) - self.update() - elif key == QtCore.Qt.Key_Up: - self.verticalScrollBar().setValue(self.verticalScrollBar().value()-20 ) - self.update() - elif key == QtCore.Qt.Key_Down: - self.verticalScrollBar().setValue(self.verticalScrollBar().value()+20 ) - self.update() - else: - if not self.focus_node: - self.focus_node = self.scene().tree - - if key == QtCore.Qt.Key_Left: - if self.focus_node.up: - new_focus_node = self.focus_node.up - self.set_focus(new_focus_node) - elif key == QtCore.Qt.Key_Right: - if self.focus_node.children: - new_focus_node = self.focus_node.children[0] - self.set_focus(new_focus_node) - elif key == QtCore.Qt.Key_Up: - if self.focus_node.up: - i = self.focus_node.up.children.index(self.focus_node) - if i>0: - new_focus_node = self.focus_node.up.children[i-1] - self.set_focus(new_focus_node) - elif self.focus_node.up: - self.set_focus(self.focus_node.up) - - elif key == QtCore.Qt.Key_Down: - if self.focus_node.up: - i = self.focus_node.up.children.index(self.focus_node) - if i < len(self.focus_node.up.children)-1: - new_focus_node = self.focus_node.up.children[i+1] - self.set_focus(new_focus_node) - elif self.focus_node.up: - self.set_focus(self.focus_node.up) - - elif key == QtCore.Qt.Key_Escape: - self.hide_focus() - elif key == QtCore.Qt.Key_Enter or\ - key == QtCore.Qt.Key_Return: - self.prop_table.tableView.setFocus() - elif key == QtCore.Qt.Key_Space: - self.highlight_node(self.focus_node, fullRegion=True, - bg=random_color(l=0.5, s=0.5), - permanent=True) - QtGui.QGraphicsView.keyPressEvent(self,e) - - def mouseReleaseEvent(self, e): - self.scene().view.hide_focus() - curr_pos = self.mapToScene(e.pos()) - - x = min(self.selector.startPoint.x(),curr_pos.x()) - y = min(self.selector.startPoint.y(),curr_pos.y()) - w = max(self.selector.startPoint.x(),curr_pos.x()) - x - h = max(self.selector.startPoint.y(),curr_pos.y()) - y - if self.selector.startPoint == curr_pos: - self.selector.setVisible(False) - self.selector.setActive(False) - QtGui.QGraphicsView.mouseReleaseEvent(self,e) - - def mousePressEvent(self,e): - pos = self.mapToScene(e.pos()) - x, y = pos.x(), pos.y() - self.selector.setRect(x, y, 0,0) - self.selector.startPoint = QtCore.QPointF(x, y) - self.selector.setActive(True) - self.selector.setVisible(True) - QtGui.QGraphicsView.mousePressEvent(self,e) - - def mouseMoveEvent(self,e): - curr_pos = self.mapToScene(e.pos()) - if self.selector.isActive(): - x = min(self.selector.startPoint.x(),curr_pos.x()) - y = min(self.selector.startPoint.y(),curr_pos.y()) - w = max(self.selector.startPoint.x(),curr_pos.x()) - x - h = max(self.selector.startPoint.y(),curr_pos.y()) - y - self.selector.setRect(x,y,w,h) - QtGui.QGraphicsView.mouseMoveEvent(self, e) - - -class _BasicNodeActions(object): - """ Should be added as ActionDelegator """ - - @staticmethod - def init(obj): - obj.setCursor(QtCore.Qt.PointingHandCursor) - obj.setAcceptsHoverEvents(True) - - @staticmethod - def hoverEnterEvent (obj, e): - print "HOLA" - - @staticmethod - def hoverLeaveEvent(obj, e): - print "ADIOS" - - @staticmethod - def mousePressEvent(obj, e): - print "Click" - - @staticmethod - def mouseReleaseEvent(obj, e): - if e.button() == QtCore.Qt.RightButton: - obj.showActionPopup() - elif e.button() == QtCore.Qt.LeftButton: - obj.scene().view.set_focus(obj.node) - #obj.scene().view.prop_table.update_properties(obj.node) - - @staticmethod - def hoverEnterEvent (self, e): - self.scene().view.highlight_node(self.node, fullRegion=True) - - @staticmethod - def hoverLeaveEvent(self,e): - self.scene().view.unhighlight_node(self.node) - - - - - - diff --git a/ete2/treeview/qt4_gui.pyc b/ete2/treeview/qt4_gui.pyc deleted file mode 100644 index 8fce2ec..0000000 Binary files a/ete2/treeview/qt4_gui.pyc and /dev/null differ diff --git a/ete2/treeview/qt4_rect_render.py b/ete2/treeview/qt4_rect_render.py deleted file mode 100644 index ec3256a..0000000 --- a/ete2/treeview/qt4_rect_render.py +++ /dev/null @@ -1,111 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -from PyQt4 import QtCore, QtGui -from main import _leaf - -class RectPartition(QtGui.QGraphicsRectItem): - def __init__(self, *args): - QtGui.QGraphicsRectItem.__init__(self, *args) - self.drawbg = False - self.nodeRegion = QtCore.QRectF() - self.facesRegion = QtCore.QRectF() - self.fullRegion = QtCore.QRectF() - - def paint(self, painter, option, index): - if self.drawbg: - painter.setClipRect( option.exposedRect ) - return QtGui.QGraphicsRectItem.paint(self, painter, option, index) - -def get_partition_center(n, n2i, n2f): - down_h = n2f[n]["branch-bottom"].h - up_h = n2f[n]["branch-top"].h - - #right_h = max(n2f[n]["branch-right"].h, n.img_style["size"]) /2 - right_h = n2i[n].nodeRegion.height()/2 - - up_h = max(right_h, up_h) - down_h = max(right_h, down_h) - - fullR = n2i[n].fullRegion - - if _leaf(n): - center = fullR.height()/2 - else: - first_child_part = n2i[n.children[0]] - last_child_part = n2i[n.children[-1]] - c1 = first_child_part.start_y + first_child_part.center - c2 = last_child_part.start_y + last_child_part.center - center = c1 + ((c2-c1)/2) - - if up_h > center: - center = up_h - elif down_h > fullR.height() - center: - center = fullR.height() - down_h - - return center - -def init_rect_leaf_item(node, n2i, n2f): - item = n2i[node] - item.center = get_partition_center(node, n2i, n2f) - -def init_rect_node_item(node, n2i, n2f): - item = n2i[node] - all_childs_height = sum([n2i[c].fullRegion.height() for c in node.children]) - all_childs_width = max([n2i[c].fullRegion.width() for c in node.children]) - if all_childs_height > item.fullRegion.height(): - item.fullRegion.setHeight(all_childs_height) - - item.fullRegion.setWidth(all_childs_width + item.nodeRegion.width()) - - suby = 0 - subx = item.nodeRegion.width() - if item.nodeRegion.height() > all_childs_height: - suby += ((item.fullRegion.height() - all_childs_height))/2 - - for c in node.children: - cpart = n2i[c] - # Sets x and y position of child within parent - # partition (relative positions) - cpart.setParentItem(item) - cpart.setPos(subx, suby) - cpart.start_y = suby - suby += cpart.fullRegion.height() - item.center = get_partition_center(node, n2i, n2f) diff --git a/ete2/treeview/qt4_rect_render.pyc b/ete2/treeview/qt4_rect_render.pyc deleted file mode 100644 index 769854a..0000000 Binary files a/ete2/treeview/qt4_rect_render.pyc and /dev/null differ diff --git a/ete2/treeview/qt4_render.py b/ete2/treeview/qt4_render.py deleted file mode 100644 index 4954819..0000000 --- a/ete2/treeview/qt4_render.py +++ /dev/null @@ -1,1104 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -import math -import re # Used to fix SVG exporting - -from PyQt4 import QtCore, QtGui, QtSvg - -import qt4_circular_render as crender -import qt4_rect_render as rrender - -from main import _leaf, NodeStyle, _FaceAreas, tracktime, TreeStyle -from node_gui_actions import _NodeActions as _ActionDelegator -from qt4_face_render import update_node_faces, _FaceGroupItem, _TextFaceItem -from templates import _DEFAULT_STYLE, apply_template -import faces - -## | General scheme of node content -## |==========================================================================================================================| -## | fullRegion | -## | nodeRegion |================================================================================| -## | | fullRegion || -## | | nodeRegion |=======================================|| -## | | | fullRegion ||| -## | | | nodeRegion ||| -## | | | |branch_length | nodeSize | facesRegion||| -## | | branch_length | nodesize|faces-right |=======================================|| -## | | |(facesRegion)|=======================================|| -## | | | fullRegion || -## | | | nodeRegion || -## | faces-top | | | | branch_length | nodeSize | facesRegion|| -## | branch_length | NodeSize |faces-right | |=======================================|| -## | faces-bottom | |(facesRegion)|================================================================================| -## | |=======================================| | -## | | fullRegion | | -## | | nodeRegion | | -## | | branch_length | nodeSize | facesRegion| | -## | |=======================================| | -## |==========================================================================================================================| - -class _CircleItem(QtGui.QGraphicsEllipseItem, _ActionDelegator): - def __init__(self, node): - self.node = node - d = node.img_style["size"] - QtGui.QGraphicsEllipseItem.__init__(self, 0, 0, d, d) - _ActionDelegator.__init__(self) - - self.setBrush(QtGui.QBrush(QtGui.QColor(self.node.img_style["fgcolor"]))) - self.setPen(QtGui.QPen(QtGui.QColor(self.node.img_style["fgcolor"]))) - -class _RectItem(QtGui.QGraphicsRectItem, _ActionDelegator): - def __init__(self, node): - self.node = node - d = node.img_style["size"] - QtGui.QGraphicsRectItem.__init__(self, 0, 0, d, d) - _ActionDelegator.__init__(self) - self.setBrush(QtGui.QBrush(QtGui.QColor(self.node.img_style["fgcolor"]))) - self.setPen(QtGui.QPen(QtGui.QColor(self.node.img_style["fgcolor"]))) - -class _SphereItem(QtGui.QGraphicsEllipseItem, _ActionDelegator): - def __init__(self, node): - self.node = node - d = node.img_style["size"] - r = d/2.0 - QtGui.QGraphicsEllipseItem.__init__(self, 0, 0, d, d) - _ActionDelegator.__init__(self) - #self.setBrush(QtGui.QBrush(QtGui.QColor(self.node.img_style["fgcolor"]))) - self.setPen(QtGui.QPen(QtGui.QColor(self.node.img_style["fgcolor"]))) - gradient = QtGui.QRadialGradient(r, r, r,(d)/3,(d)/3) - gradient.setColorAt(0.05, QtCore.Qt.white); - gradient.setColorAt(1, QtGui.QColor(self.node.img_style["fgcolor"])); - self.setBrush(QtGui.QBrush(gradient)) - # self.setPen(QtCore.Qt.NoPen) - -class _EmptyItem(QtGui.QGraphicsItem): - def __init__(self, parent=None): - QtGui.QGraphicsItem.__init__(self) - self.setParentItem(parent) - - # qt4.6+ Only - try: - self.setFlags(QtGui.QGraphicsItem.ItemHasNoContents) - except: - pass - - def boundingRect(self): - return QtCore.QRectF(0,0,0,0) - - def paint(self, *args, **kargs): - return - -class _TreeItem(QtGui.QGraphicsRectItem): - def __init__(self, parent=None): - QtGui.QGraphicsRectItem.__init__(self) - self.setParentItem(parent) - self.n2i = {} - self.n2f = {} - -class _NodeItem(_EmptyItem): - def __init__(self, node, parent): - _EmptyItem.__init__(self, parent) - self.node = node - self.nodeRegion = QtCore.QRectF() - self.facesRegion = QtCore.QRectF() - self.fullRegion = QtCore.QRectF() - self.highlighted = False - -class _NodeLineItem(QtGui.QGraphicsLineItem, _ActionDelegator): - def __init__(self, node, *args, **kargs): - self.node = node - QtGui.QGraphicsLineItem.__init__(self, *args, **kargs) - _ActionDelegator.__init__(self) - def paint(self, painter, option, widget): - QtGui.QGraphicsLineItem.paint(self, painter, option, widget) - -class _LineItem(QtGui.QGraphicsLineItem): - def paint(self, painter, option, widget): - QtGui.QGraphicsLineItem.paint(self, painter, option, widget) - -class _PointerItem(QtGui.QGraphicsRectItem): - def __init__(self, parent=None): - QtGui.QGraphicsRectItem.__init__(self,0,0,0,0, parent) - self.color = QtGui.QColor("blue") - self._active = False - self.setBrush(QtGui.QBrush(QtCore.Qt.NoBrush)) - - def paint(self, p, option, widget): - p.setPen(self.color) - p.drawRect(self.rect()) - return - # Draw info text - font = QtGui.QFont("Arial",13) - text = "%d selected." % len(self.get_selected_nodes()) - textR = QtGui.QFontMetrics(font).boundingRect(text) - if self.rect().width() > textR.width() and \ - self.rect().height() > textR.height()/2.0 and 0: # OJO !!!! - p.setPen(QtGui.QPen(self.color)) - p.setFont(QtGui.QFont("Arial",13)) - p.drawText(self.rect().bottomLeft().x(),self.rect().bottomLeft().y(),text) - - def get_selected_nodes(self): - selPath = QtGui.QPainterPath() - selPath.addRect(self.rect()) - self.scene().setSelectionArea(selPath) - return [i.node for i in self.scene().selectedItems()] - - def setActive(self,bool): - self._active = bool - - def isActive(self): - return self._active - -class _TreeScene(QtGui.QGraphicsScene): - def __init__(self): - QtGui.QGraphicsScene.__init__(self) - self.view = None - - def init_values(self, tree, img, n2i, n2f): - self.master_item = _EmptyItem() - self.tree = tree - self.n2i = n2i - self.n2f = n2f - self.img = img - - def draw(self): - self.img._scale = None - tree_item, self.n2i, self.n2f = render(self.tree, self.img) - if self.master_item: - self.removeItem(self.master_item) - tree_item, n2i, n2f = render(self.tree, self.img) - self.init_values(self.tree, self.img, n2i, n2f) - self.addItem(self.master_item) - tree_item.setParentItem(self.master_item) - self.setSceneRect(tree_item.rect()) - -#@tracktime -def render(root_node, img, hide_root=False): - '''main render function. hide_root option is used when render - trees as Faces - - ''' - mode = img.mode - orientation = img.orientation - - arc_span = img.arc_span - - layout_fn = img._layout_handler - - parent = _TreeItem() - n2i = parent.n2i # node to items - n2f = parent.n2f # node to faces - - parent.bg_layer = _EmptyItem(parent) - parent.tree_layer = _EmptyItem(parent) - parent.float_layer = _EmptyItem(parent) - parent.float_behind_layer = _EmptyItem(parent) - - TREE_LAYERS = [parent.bg_layer, parent.tree_layer, - parent.float_layer, parent.float_behind_layer] - - parent.bg_layer.setZValue(0) - parent.tree_layer.setZValue(2) - - parent.float_behind_layer.setZValue(1) - parent.float_layer.setZValue(3) - - # This could be used to handle aligned faces in internal - # nodes. - virtual_leaves = 0 - - if img.show_branch_length: - bl_face = faces.AttrFace("dist", fsize=8, ftype="Arial", fgcolor="black", formatter = "%0.3g") - if img.show_branch_support: - su_face = faces.AttrFace("support", fsize=8, ftype="Arial", fgcolor="darkred", formatter = "%0.3g") - if img.show_leaf_name: - na_face = faces.AttrFace("name", fsize=10, ftype="Arial", fgcolor="black") - - for n in root_node.traverse(is_leaf_fn=_leaf): - set_style(n, layout_fn) - - if img.show_branch_length: - faces.add_face_to_node(bl_face, n, 0, position="branch-top") - - if not _leaf(n) and img.show_branch_support: - faces.add_face_to_node(su_face, n, 0, position="branch-bottom") - - if _leaf(n) and img.show_leaf_name: - faces.add_face_to_node(na_face, n, 0, position="branch-right") - - if _leaf(n):# or len(n.img_style["_faces"]["aligned"]): - virtual_leaves += 1 - - update_node_faces(n, n2f, img) - - rot_step = float(arc_span) / virtual_leaves - #rot_step = float(arc_span) / len([n for n in root_node.traverse() if _leaf(n)]) - - # Calculate optimal branch length - if img._scale is not None: - init_items(root_node, parent, n2i, n2f, img, rot_step, hide_root) - elif img.scale is None: - # create items and calculate node dimensions skipping branch lengths - init_items(root_node, parent, n2i, n2f, img, rot_step, hide_root) - if mode == 'r': - if img.optimal_scale_level == "full": - scales = [(i.widths[1]/n.dist) for n,i in n2i.iteritems() if n.dist] - img._scale = max(scales) if scales else 0.0 - else: - farthest, dist = root_node.get_farthest_leaf(topology_only=img.force_topology) - img._scale = img.tree_width / dist if dist else 0.0 - update_branch_lengths(root_node, n2i, n2f, img) - else: - img._scale = crender.calculate_optimal_scale(root_node, n2i, rot_step, img) - #print "OPTIMAL circular scale", img._scale - update_branch_lengths(root_node, n2i, n2f, img) - init_items(root_node, parent, n2i, n2f, img, rot_step, hide_root) - else: - # create items and calculate node dimensions CONSIDERING branch lengths - img._scale = img.scale - init_items(root_node, parent, n2i, n2f, img, rot_step, hide_root) - - #print "USING scale", img._scale - # Draw node content - for node in root_node.traverse(is_leaf_fn=_leaf): - if node is not root_node or not hide_root: - render_node_content(node, n2i, n2f, img) - - # Adjust content to rect or circular layout - mainRect = parent.rect() - - if mode == "c": - tree_radius = crender.render_circular(root_node, n2i, rot_step) - mainRect.adjust(-tree_radius, -tree_radius, tree_radius, tree_radius) - else: - iwidth = n2i[root_node].fullRegion.width() - iheight = n2i[root_node].fullRegion.height() - mainRect.adjust(0, 0, iwidth, iheight) - tree_radius = iwidth - - # Add extra layers: aligned faces, floating faces, node - # backgrounds, etc. The order by which the following methods are - # called IS IMPORTANT - render_floatings(n2i, n2f, img, parent.float_layer, parent.float_behind_layer) - - aligned_region_width = render_aligned_faces(img, mainRect, parent.tree_layer, n2i, n2f) - - render_backgrounds(img, mainRect, parent.bg_layer, n2i, n2f) - - # rotate if necessary in circular images. flip and adjust if mirror orientation. - adjust_faces_to_tranformations(img, mainRect, n2i, n2f, TREE_LAYERS) - - # Rotate main image if necessary - parent.setRect(mainRect) - parent.setPen(QtGui.QPen(QtCore.Qt.NoPen)) - - if img.rotation: - rect = parent.boundingRect() - x = rect.x() + (rect.width()/2.0) - y = rect.y() + (rect.height()/2.0) - parent.setTransform(QtGui.QTransform().translate(x, y).rotate(img.rotation).translate(-x, -y)) - - # Creates the main tree item that will act as frame for the whole image - frame = QtGui.QGraphicsRectItem() - parent.setParentItem(frame) - mainRect = parent.mapToScene(mainRect).boundingRect() - - mainRect.adjust(-img.margin_left, -img.margin_top, \ - img.margin_right, img.margin_bottom) - - # Fix negative coordinates, so main item always starts at 0,0 - topleft = mainRect.topLeft() - _x = abs(topleft.x()) if topleft.x() < 0 else 0 - _y = abs(topleft.y()) if topleft.y() < 0 else 0 - if _x or _y: - parent.moveBy(_x, _y) - mainRect.adjust(_x, _y, _x, _y) - - # Add extra components and adjust mainRect to them - add_legend(img, mainRect, frame) - add_title(img, mainRect, frame) - add_scale(img, mainRect, frame) - frame.setRect(mainRect) - - # Draws a border around the tree - if not img.show_border: - frame.setPen(QtGui.QPen(QtCore.Qt.NoPen)) - else: - frame.setPen(QtGui.QPen(QtGui.QColor("black"))) - - return frame, n2i, n2f - -def adjust_faces_to_tranformations(img, mainRect, n2i, n2f, tree_layers): - if img.mode == "c": - rotate_inverted_faces(n2i, n2f, img) - elif img.mode == "r" and img.orientation == 1: - for layer in tree_layers: - layer.setTransform(QtGui.QTransform().translate(0, 0).scale(-1,1).translate(0, 0)) - layer.moveBy(mainRect.width(),0) - for faceblock in n2f.itervalues(): - for pos, fb in faceblock.iteritems(): - fb.flip_hz() - -def add_legend(img, mainRect, parent): - if img.legend: - legend = _FaceGroupItem(img.legend, None) - legend.setup_grid() - legend.render() - lg_w, lg_h = legend.get_size() - dw = max(0, lg_w-mainRect.width()) - legend.setParentItem(parent) - if img.legend_position == 1: - mainRect.adjust(0, -lg_h, dw, 0) - legend.setPos(mainRect.topLeft()) - elif img.legend_position == 2: - mainRect.adjust(0, -lg_h, dw, 0) - pos = mainRect.topRight() - legend.setPos(pos.x()-lg_w, pos.y()) - elif img.legend_position == 3: - legend.setPos(mainRect.bottomLeft()) - mainRect.adjust(0, 0, dw, lg_h) - elif img.legend_position == 4: - pos = mainRect.bottomRight() - legend.setPos(pos.x()-lg_w, pos.y()) - mainRect.adjust(0, 0, dw, lg_h) - -def add_title(img, mainRect, parent): - if img.title: - title = _FaceGroupItem(img.title, None) - title.setup_grid() - title.render() - lg_w, lg_h = title.get_size() - dw = max(0, lg_w-mainRect.width()) - title.setParentItem(parent) - mainRect.adjust(0, -lg_h, dw, 0) - title.setPos(mainRect.topLeft()) - -def add_legend(img, mainRect, parent): - if img.legend: - legend = _FaceGroupItem(img.legend, None) - legend.setup_grid() - legend.render() - lg_w, lg_h = legend.get_size() - dw = max(0, lg_w-mainRect.width()) - legend.setParentItem(parent) - if img.legend_position == 1: - mainRect.adjust(0, -lg_h, dw, 0) - legend.setPos(mainRect.topLeft()) - elif img.legend_position == 2: - mainRect.adjust(0, -lg_h, dw, 0) - pos = mainRect.topRight() - legend.setPos(pos.x()-lg_w, pos.y()) - elif img.legend_position == 3: - legend.setPos(mainRect.bottomLeft()) - mainRect.adjust(0, 0, dw, lg_h) - elif img.legend_position == 4: - pos = mainRect.bottomRight() - legend.setPos(pos.x()-lg_w, pos.y()) - mainRect.adjust(0, 0, dw, lg_h) - -def add_scale(img, mainRect, parent): - if img.show_scale: - length=50 - scaleItem = _EmptyItem() - customPen = QtGui.QPen(QtGui.QColor("black"), 1) - line = QtGui.QGraphicsLineItem(scaleItem) - line2 = QtGui.QGraphicsLineItem(scaleItem) - line3 = QtGui.QGraphicsLineItem(scaleItem) - line.setPen(customPen) - line2.setPen(customPen) - line3.setPen(customPen) - - line.setLine(0, 5, length, 5) - line2.setLine(0, 0, 0, 10) - line3.setLine(length, 0, length, 10) - - length_text = float(length) / img._scale if img._scale else 0.0 - #scale_text = "%0.2f\n(1 branch unit = %d pixels)" % (length_text, round(img._scale)) - scale_text = "%0.2f" % (length_text) - scale = QtGui.QGraphicsSimpleTextItem(scale_text) - scale.setParentItem(scaleItem) - scale.setPos(0, 10) - - if img.force_topology: - wtext = "Force topology is enabled!\nBranch lengths do not represent real values." - warning_text = QtGui.QGraphicsSimpleTextItem(wtext) - warning_text.setFont(QtGui.QFont("Arial", 8)) - warning_text.setBrush( QtGui.QBrush(QtGui.QColor("darkred"))) - warning_text.setPos(0, 32) - warning_text.setParentItem(scaleItem) - else: - line = QtGui.QGraphicsLineItem(scaleItem) - line2 = QtGui.QGraphicsLineItem(scaleItem) - line3 = QtGui.QGraphicsLineItem(scaleItem) - line.setPen(customPen) - line2.setPen(customPen) - line3.setPen(customPen) - - line.setLine(0, 5, length, 5) - line2.setLine(0, 0, 0, 10) - line3.setLine(length, 0, length, 10) - #scale_text = "%0.2f" % (float(length) / img._scale) - scale = QtGui.QGraphicsSimpleTextItem(scale_text) - scale.setParentItem(scaleItem) - scale.setPos(0, 10) - - scaleItem.setParentItem(parent) - dw = max(0, length-mainRect.width()) - scaleItem.setPos(mainRect.bottomLeft()) - mainRect.adjust(0,0,dw, length) - -def rotate_inverted_faces(n2i, n2f, img): - for node, faceblock in n2f.iteritems(): - item = n2i[node] - if item.rotation > 90 and item.rotation < 270: - for pos, fb in faceblock.iteritems(): - fb.rotate(181) - -def render_backgrounds(img, mainRect, bg_layer, n2i, n2f): - - if img.mode == "c": - max_r = mainRect.width()/2.0 - else: - max_r = mainRect.width() - - for node, item in n2i.iteritems(): - if _leaf(node): - first_c = n2i[node] - last_c = n2i[node] - else: - first_c = n2i[node.children[0]] - last_c = n2i[node.children[-1]] - - if img.mode == "c": - h = item.effective_height - angle_start = first_c.full_start - angle_end = last_c.full_end - parent_radius = getattr(n2i.get(node.up, None), "radius", 0) - base = parent_radius + item.nodeRegion.width() - - if node.img_style["node_bgcolor"].upper() != "#FFFFFF": - bg1 = crender._ArcItem() - r = math.sqrt(base**2 + h**2) - bg1.set_arc(0, 0, parent_radius, r, angle_start, angle_end) - bg1.setParentItem(item.content.bg) - bg1.setPen(QtGui.QPen(QtGui.QColor(node.img_style["node_bgcolor"]))) - bg1.setBrush(QtGui.QBrush(QtGui.QColor(node.img_style["node_bgcolor"]))) - - if node.img_style["faces_bgcolor"].upper() != "#FFFFFF": - bg2 = crender._ArcItem() - r = math.sqrt(base**2 + h**2) - bg2.set_arc(0, 0, parent_radius, item.radius, angle_start, angle_end) - bg2.setParentItem(item.content) - bg2.setPen(QtGui.QPen(QtGui.QColor(node.img_style["faces_bgcolor"]))) - bg2.setBrush(QtGui.QBrush(QtGui.QColor(node.img_style["faces_bgcolor"]))) - - if node.img_style["bgcolor"].upper() != "#FFFFFF": - bg = crender._ArcItem() - bg.set_arc(0, 0, parent_radius, max_r, angle_start, angle_end) - bg.setPen(QtGui.QPen(QtGui.QColor(node.img_style["bgcolor"]))) - bg.setBrush(QtGui.QBrush(QtGui.QColor(node.img_style["bgcolor"]))) - bg.setParentItem(bg_layer) - bg.setZValue(item.zValue()) - - if img.mode == "r": - if node.img_style["bgcolor"].upper() != "#FFFFFF": - bg = QtGui.QGraphicsRectItem() - pos = item.content.mapToScene(0, 0) - bg.setPos(pos.x(), pos.y()) - bg.setRect(0, 0, max_r-pos.x(), item.fullRegion.height()) - bg.setPen(QtGui.QPen(QtGui.QColor(node.img_style["bgcolor"]))) - bg.setBrush(QtGui.QBrush(QtGui.QColor(node.img_style["bgcolor"]))) - bg.setParentItem(bg_layer) - bg.setZValue(item.zValue()) - -def set_node_size(node, n2i, n2f, img): - scale = img._scale - min_separation = img.min_leaf_separation - - item = n2i[node] - if img.force_topology: - branch_length = item.branch_length = 25 - else: - branch_length = item.branch_length = float(node.dist * scale) - - # Organize faces by groups - #faceblock = update_node_faces(node, n2f, img) - faceblock = n2f[node] - aligned_height = 0 - if _leaf(node): - if img.mode == "r": - aligned_height = faceblock["aligned"].h - elif img.mode == "c": - # aligned faces in circular mode are adjusted afterwords. The - # min radius of the largest aligned faces will be calculated. - pass - - # Total height required by the node. I cannot sum up the height of - # all elements, since the position of some of them are forced to - # be on top or at the bottom of branches. This fact can produce - # and unbalanced nodeRegion center. Here, I only need to know - # about the imbalance size to correct node height. The center will - # be calculated later according to the parent position. - top_half_h = ( (node.img_style["size"]/2.0) + - node.img_style["hz_line_width"]/2.0 + - faceblock["branch-top"].h ) - - bottom_half_h =( (node.img_style["size"]/2.0) + - node.img_style["hz_line_width"]/2.0 + - faceblock["branch-bottom"].h ) - - h1 = top_half_h + bottom_half_h - h2 = max(faceblock["branch-right"].h, \ - aligned_height, \ - min_separation ) - h = max(h1, h2) - imbalance = abs(top_half_h - bottom_half_h) - if imbalance > h2/2.0: - h += imbalance - (h2/2.0) - - # This adds a vertical margin around the node elements - h += img.branch_vertical_margin - - # Total width required by the node - w = sum([max(branch_length + node.img_style["size"], - faceblock["branch-top"].w + node.img_style["size"], - faceblock["branch-bottom"].w + node.img_style["size"], - ), - faceblock["branch-right"].w] - ) - w += node.img_style["vt_line_width"] - - # rightside faces region - item.facesRegion.setRect(0, 0, faceblock["branch-right"].w, h) - - # Node region - item.nodeRegion.setRect(0, 0, w, h) - - # This is the node total region covered by the node - item.fullRegion.setRect(0, 0, w, h) - -def render_node_content(node, n2i, n2f, img): - style = node.img_style - item = n2i[node] - item.content = _EmptyItem(item) - - nodeR = item.nodeRegion - facesR = item.facesRegion - center = item.center - branch_length = item.branch_length - - # Node points - ball_size = style["size"] - - vlw = style["vt_line_width"] if not _leaf(node) and len(node.children) > 1 else 0.0 - - face_start_x = nodeR.width() - facesR.width() - vlw - ball_start_x = face_start_x - ball_size - - if ball_size: - if node.img_style["shape"] == "sphere": - node_ball = _SphereItem(node) - elif node.img_style["shape"] == "circle": - node_ball = _CircleItem(node) - elif node.img_style["shape"] == "square": - node_ball = _RectItem(node) - - node_ball.setPos(ball_start_x, center-(ball_size/2.0)) - - #from qt4_gui import _BasicNodeActions - #node_ball.delegate = _BasicNodeActions() - #node_ball.setAcceptsHoverEvents(True) - #node_ball.setCursor(QtCore.Qt.PointingHandCursor) - - else: - node_ball = None - - # Branch line to parent - pen = QtGui.QPen() - set_pen_style(pen, style["hz_line_type"]) - pen.setColor(QtGui.QColor(style["hz_line_color"])) - pen.setWidth(style["hz_line_width"]) - pen.setCapStyle(QtCore.Qt.FlatCap) - #pen.setCapStyle(QtCore.Qt.RoundCap) - #pen.setCapStyle(QtCore.Qt.SquareCap) - #pen.setJoinStyle(QtCore.Qt.RoundJoin) - hz_line = _LineItem() - hz_line = _NodeLineItem(node) - hz_line.setPen(pen) - - join_fix = 0 - if node.up and node.up.img_style["vt_line_width"]: - join_fix = node.up.img_style["vt_line_width"] - - hz_line.setLine(-join_fix, center, branch_length, center) - - if img.complete_branch_lines_when_necessary: - extra_line = _LineItem(branch_length, center, ball_start_x, center) - pen = QtGui.QPen() - item.extra_branch_line = extra_line - set_pen_style(pen, img.extra_branch_line_type) - pen.setColor(QtGui.QColor(img.extra_branch_line_color)) - pen.setCapStyle(QtCore.Qt.FlatCap) - pen.setWidth(style["hz_line_width"]) - extra_line.setPen(pen) - else: - extra_line = None - - # Attach branch-right faces to child - fblock_r = n2f[node]["branch-right"] - fblock_r.render() - fblock_r.setPos(face_start_x, center-fblock_r.h/2.0) - - # Attach branch-bottom faces to child - fblock_b = n2f[node]["branch-bottom"] - fblock_b.render() - fblock_b.setPos(item.widths[0], center + style["hz_line_width"]/2.0) - - # Attach branch-top faces to child - fblock_t = n2f[node]["branch-top"] - fblock_t.render() - fblock_t.setPos(item.widths[0], center - fblock_t.h - style["hz_line_width"]/2.0) - - # Vertical line - if not _leaf(node): - if img.mode == "c": - vt_line = QtGui.QGraphicsPathItem() - - elif img.mode == "r": - vt_line = _LineItem(item) - first_child = node.children[0] - last_child = node.children[-1] - first_child_part = n2i[node.children[0]] - last_child_part = n2i[node.children[-1]] - c1 = first_child_part.start_y + first_child_part.center - c2 = last_child_part.start_y + last_child_part.center - fx = nodeR.width() - (vlw/2.0) - if first_child.img_style["hz_line_width"] > 0: - c1 -= (first_child.img_style["hz_line_width"] / 2.0) - if last_child.img_style["hz_line_width"] > 0: - c2 += (last_child.img_style["hz_line_width"] / 2.0) - vt_line.setLine(fx, c1, fx, c2) - - pen = QtGui.QPen() - set_pen_style(pen, style["vt_line_type"]) - pen.setColor(QtGui.QColor(style["vt_line_color"])) - pen.setWidth(style["vt_line_width"]) - pen.setCapStyle(QtCore.Qt.FlatCap) - #pen.setCapStyle(QtCore.Qt.RoundCap) - #pen.setCapStyle(QtCore.Qt.SquareCap) - vt_line.setPen(pen) - item.vt_line = vt_line - else: - vt_line = None - - item.bg = QtGui.QGraphicsItemGroup() - item.movable_items = [] #QtGui.QGraphicsItemGroup() - item.static_items = [] #QtGui.QGraphicsItemGroup() - - # Items fow which coordinates are exported in the image map - item.mapped_items = [node_ball, fblock_r, fblock_b, fblock_t] - - for i in [node_ball, fblock_r, fblock_b, fblock_t]: - if i: - #item.movable_items.addToGroup(i) - item.movable_items.append(i) - i.setParentItem(item.content) - - for i in [vt_line, extra_line, hz_line]: - if i: - #item.static_items.addToGroup(i) - item.static_items.append(i) - i.setParentItem(item.content) - - #item.movable_items.setParentItem(item.content) - #item.static_items.setParentItem(item.content) - -def set_pen_style(pen, line_style): - if line_style == 0: - pen.setStyle(QtCore.Qt.SolidLine) - elif line_style == 1: - pen.setStyle(QtCore.Qt.DashLine) - elif line_style == 2: - pen.setStyle(QtCore.Qt.DotLine) - -def set_style(n, layout_func): - #if not isinstance(getattr(n, "img_style", None), NodeStyle): - # print "Style of", n.name ,"is None" - # n.set_style() - # n.img_style = NodeStyle() - - n._temp_faces = _FaceAreas() - - for func in layout_func: - func(n) - -def render_floatings(n2i, n2f, img, float_layer, float_behind_layer): - #floating_faces = [ [node, fb["float"]] for node, fb in n2f.iteritems() if "float" in fb] - - for node, faces in n2f.iteritems(): - face_set = [ [float_layer, faces.get("float", None)], - [float_behind_layer, faces.get("float-behind",None)]] - - for parent_layer,fb in face_set: - if not fb: - continue - - item = n2i[node] - fb.setParentItem(parent_layer) - - if item.extra_branch_line: - xtra = item.extra_branch_line.line().dx() - else: - xtra = 0 - - if img.mode == "c": - # Floatings are positioned over branches - crender.rotate_and_displace(fb, item.rotation, fb.h, item.radius - item.nodeRegion.width() + xtra) - # Floatings are positioned starting from the node circle - #crender.rotate_and_displace(fb, item.rotation, fb.h, item.radius - item.nodeRegion.width()) - - elif img.mode == "r": - start = item.branch_length + xtra - fb.w #if fb.w < item.branch_length else 0.0 - fb.setPos(item.content.mapToScene(start, item.center - (fb.h/2.0))) - - z = item.zValue() - if not img.children_faces_on_top: - z = -z - - fb.setZValue(z) - fb.update_columns_size() - fb.render() - -def render_aligned_faces(img, mainRect, parent, n2i, n2f): - # Prepares and renders aligned face headers. Used to later - # place aligned faces - aligned_faces = [ [node, fb["aligned"]] for node, fb in n2f.iteritems()\ - if fb["aligned"].column2faces and _leaf(node)] - - # If no aligned faces, just return an offset of 0 pixels - if not aligned_faces: - return 0 - - # Load header and footer - if img.mode == "r": - tree_end_x = mainRect.width() - - fb_head = _FaceGroupItem(img.aligned_header, None) - fb_head.setParentItem(parent) - fb_foot = _FaceGroupItem(img.aligned_foot, None) - fb_foot.setParentItem(parent) - surroundings = [[None,fb_foot], [None, fb_head]] - mainRect.adjust(0, -fb_head.h, 0, fb_foot.h) - else: - tree_end_x = mainRect.width()/2.0 - surroundings = [] - - # Place aligned faces and calculates the max size of each - # column (needed to place column headers) - c2max_w = {} - maxh = 0 - maxh_node = None - for node, fb in aligned_faces + surroundings: - if fb.h > maxh: - maxh = fb.h - maxh_node = node - for c, w in fb.c2max_w.iteritems(): - c2max_w[c] = max(w, c2max_w.get(c,0)) - extra_width = sum(c2max_w.values()) - - # If rect mode, render header and footer - if img.mode == "r": - if img.draw_aligned_faces_as_table: - fb_head.setup_grid(c2max_w) - fb_foot.setup_grid(c2max_w) - - fb_head.render() - fb_head.setPos(tree_end_x, mainRect.top()) - fb_foot.render() - fb_foot.setPos(tree_end_x, mainRect.bottom()-fb_foot.h) - if img.orientation == 1: - fb_head.flip_hz() - fb_foot.flip_hz() - - # if no scale provided in circular mode, optimal scale is expected - # to provide the correct ending point to start drawing aligned - # faces. - elif img.mode == "c" and (img.scale or img._scale == 0) and not img.allow_face_overlap: - angle = n2i[maxh_node].angle_span - rad, off = crender.get_min_radius(1, maxh, angle, tree_end_x) - extra_width += rad - tree_end_x - tree_end_x = rad - - # Place aligned faces - for node, fb in aligned_faces: - item = n2i[node] - item.mapped_items.append(fb) - if img.draw_aligned_faces_as_table: - if img.aligned_table_style == 0: - fb.setup_grid(c2max_w, as_grid=True) - elif img.aligned_table_style == 1: - fb.setup_grid(c2max_w, as_grid=False) - - fb.render() - fb.setParentItem(item.content) - if img.mode == "c": - if node.up in n2i: - x = tree_end_x - n2i[node.up].radius - else: - x = tree_end_x - #fb.moveBy(tree_end_x, 0) - elif img.mode == "r": - x = item.mapFromScene(tree_end_x, 0).x() - - fb.setPos(x, item.center-(fb.h/2.0)) - - if img.draw_guiding_lines and _leaf(node): - # -1 is to connect the two lines, otherwise there is a pixel in between - guide_line = _LineItem(item.nodeRegion.width()-1, item.center, x, item.center) - pen = QtGui.QPen() - set_pen_style(pen, img.guiding_lines_type) - pen.setColor(QtGui.QColor(img.guiding_lines_color)) - pen.setCapStyle(QtCore.Qt.FlatCap) - pen.setWidth(node.img_style["hz_line_width"]) - guide_line.setPen(pen) - guide_line.setParentItem(item.content) - - if img.mode == "c": - mainRect.adjust(-extra_width, -extra_width, extra_width, extra_width) - else: - mainRect.adjust(0, 0, extra_width, 0) - return extra_width - -def get_tree_img_map(n2i, x_scale=1, y_scale=1): - node_list = [] - face_list = [] - nid = 0 - for n, main_item in n2i.iteritems(): - n.add_feature("_nid", str(nid)) - for item in main_item.mapped_items: - if isinstance(item, _CircleItem) \ - or isinstance(item, _SphereItem) \ - or isinstance(item, _RectItem): - - r = item.boundingRect() - rect = item.mapToScene(r).boundingRect() - x1 = x_scale * rect.x() - y1 = y_scale * rect.y() - x2 = x_scale * (rect.x() + rect.width()) - y2 = y_scale * (rect.y() + rect.height()) - node_list.append([x1, y1, x2, y2, nid, None]) - elif isinstance(item, _FaceGroupItem): - if item.column2faces: - for f in item.childItems(): - r = f.boundingRect() - rect = f.mapToScene(r).boundingRect() - x1 = x_scale * rect.x() - y1 = y_scale * rect.y() - x2 = x_scale * (rect.x() + rect.width()) - y2 = y_scale * (rect.y() + rect.height()) - if isinstance(f, _TextFaceItem): - face_list.append([x1, y1, x2, y2, nid, str(f.text())]) - else: - face_list.append([x1, y1, x2, y2, nid, None]) - - nid += 1 - - return {"nodes": node_list, "faces": face_list} - -#@tracktime -def init_items(root_node, parent, n2i, n2f, img, rot_step, hide_root): - # ::: Precalculate values ::: - visited = set() - to_visit = [] - to_visit.append(root_node) - last_rotation = img.arc_start - depth = 1 - while to_visit: - node = to_visit[-1] - finished = True - if node not in n2i: - # Set style according to layout function - item = n2i[node] = _NodeItem(node, parent.tree_layer) - depth += 1 - - item.setZValue(depth) - if node is root_node and hide_root: - pass - else: - init_node_dimensions(node, item, n2f[node], img) - #set_node_size(node, n2i, n2f, img) - - if not _leaf(node): - # visit children starting from left to right. Very - # important!! check all children[-1] and children[0] - for c in reversed(node.children): - if c not in visited: - to_visit.append(c) - finished = False - # :: pre-order code here :: - if not finished: - continue - else: - to_visit.pop(-1) - visited.add(node) - - # :: Post-order visits. Leaves are already visited here :: - if img.mode == "c": - if _leaf(node): - crender.init_circular_leaf_item(node, n2i, n2f, last_rotation, rot_step) - last_rotation += rot_step - else: - crender.init_circular_node_item(node, n2i, n2f) - - elif img.mode == "r": - if _leaf(node): - rrender.init_rect_leaf_item(node, n2i, n2f) - else: - rrender.init_rect_node_item(node, n2i, n2f) - - -def init_node_dimensions(node, item, faceblock, img): - """Calculates width and height of all different subparts and faces - of a given node. Branch lengths are not taken into account, so some - dimensions must be adjusted after setting a valid scale. - """ - - min_separation = img.min_leaf_separation - - if _leaf(node): - aligned_height = faceblock["aligned"].h - aligned_width = faceblock["aligned"].w - else: - aligned_height = 0 - aligned_width = 0 - - ndist = 1.0 if img.force_topology else node.dist - item.branch_length = (ndist * img._scale) if img._scale else 0 - ## Calculate dimensions of the different node regions - ## - ## - ## | - ## | ------ - ## b-top --------- | | | - ## xoff-------------- O |b-right| | |alg | - ## b-bottom --------- | | | - ## | ------ - ## | - ## - ## 0 1 2 3 4 5 - ## - - item.xoff = 0.0 - # widths - w1 = max(faceblock["branch-bottom"].w, faceblock["branch-top"].w) - w0 = item.branch_length - w1 if item.branch_length > w1 else 0 - w2 = node.img_style["size"] - w3 = faceblock["branch-right"].w - w4 = node.img_style["vt_line_width"] if not _leaf(node) and len(node.children) > 1 else 0.0 - w5 = 0 - # heights - h0 = node.img_style["hz_line_width"] - h1 = node.img_style["hz_line_width"] + faceblock["branch-top"].h + faceblock["branch-bottom"].h - h2 = node.img_style["size"] - h3 = faceblock["branch-right"].h - h4 = 0 - h5 = aligned_height - - # ignore face heights if requested - if img.mode == "c" and img.allow_face_overlap: - h1, h3, h5 = 0, 0, 0 - - item.heights = [h0, h1, h2, h3, h4, h5] - item.widths = [w0, w1, w2, w3, w4, w5] - - # Calculate total node size - total_w = sum([w0, w1, w2, w3, w4, item.xoff]) # do not count aligned faces - - if img.mode == "c": - max_h = max(item.heights[:4] + [min_separation]) - elif img.mode == "r": - max_h = max(item.heights + [min_separation]) - - max_h += img.branch_vertical_margin - - # correct possible unbalanced block in branch faces - h_imbalance = abs(faceblock["branch-top"].h - faceblock["branch-bottom"].h) - if h_imbalance + h1 > max_h: - max_h += h_imbalance - - item.facesRegion.setRect(0, 0, w3, max_h) - item.nodeRegion.setRect(0, 0, total_w, max_h) - item.fullRegion.setRect(0, 0, total_w, max_h) - -def update_branch_lengths(tree, n2i, n2f, img): - for node in tree.traverse("postorder", is_leaf_fn=_leaf): - item = n2i[node] - ndist = 1.0 if img.force_topology else node.dist - item.branch_length = ndist * img._scale - w0 = 0 - - if item.branch_length > item.widths[1]: - w0 = item.widths[0] = item.branch_length - item.widths[1] - item.nodeRegion.adjust(0, 0, w0, 0) - - child_width = 0 - if not _leaf(node): - for ch in node.children: - child_width = max(child_width, n2i[ch].fullRegion.width()) - if w0 and img.mode == "r": - n2i[ch].translate(w0, 0) - item.fullRegion.setWidth(item.nodeRegion.width() + child_width) - -def init_tree_style(t, ts): - if not ts: - ts = TreeStyle() - - if not ts.layout_fn: - cl = t.__class__ - try: - ts_template = _DEFAULT_STYLE[cl] - except KeyError, e: - pass - else: - apply_template(ts, ts_template) - - return ts - diff --git a/ete2/treeview/qt4_render.pyc b/ete2/treeview/qt4_render.pyc deleted file mode 100644 index 9af4b35..0000000 Binary files a/ete2/treeview/qt4_render.pyc and /dev/null differ diff --git a/ete2/treeview/svg_colors.py b/ete2/treeview/svg_colors.py deleted file mode 100644 index 4d87337..0000000 --- a/ete2/treeview/svg_colors.py +++ /dev/null @@ -1,544 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -import random -import colorsys - -all = ["SVG_COLORS", "COLOR_SCHEMES", "random_color"] - -SVG_COLORS = set([ - "indianred", # CD5C5C 2059292 - "lightcoral", # F08080 240128128 - "salmon", # FA8072 250128114 - "darksalmon", # E9967A 233150122 - "lightsalmon", # FFA07A 255160122 - "crimson", # DC143C 2202060 - "red", # FF0000 25500 - "firebrick", # B22222 1783434 - "darkred", # 8B0000 13900 - "pink", # FFC0CB 255192203 - "lightpink", # FFB6C1 255182193 - "hotpink", # FF69B4 255105180 - "deeppink", # FF1493 25520147 - "mediumvioletred", # C71585 19921133 - "palevioletred", # DB7093 219112147 - "lightsalmon", # FFA07A 255160122 - "coral", # FF7F50 25512780 - "tomato", # FF6347 2559971 - "orangered", # FF4500 255690 - "darkorange", # FF8C00 2551400 - "orange", # FFA500 2551650 - "gold", # FFD700 2552150 - "yellow", # FFFF00 2552550 - "lightyellow", # FFFFE0 255255224 - "lemonchiffon", # FFFACD 255250205 - "lightgoldenrodyellow", # FAFAD2 250250210 - "papayawhip", # FFEFD5 255239213 - "moccasin", # FFE4B5 255228181 - "peachpuff", # FFDAB9 255218185 - "palegoldenrod", # EEE8AA 238232170 - "khaki", # F0E68C 240230140 - "darkkhaki", # BDB76B 189183107 - "lavender", # E6E6FA 230230250 - "thistle", # D8BFD8 216191216 - "plum", # DDA0DD 221160221 - "violet", # EE82EE 238130238 - "orchid", # DA70D6 218112214 - "fuchsia", # FF00FF 2550255 - "magenta", # FF00FF 2550255 - "mediumorchid", # BA55D3 18685211 - "mediumpurple", # 9370DB 147112219 - "amethyst", # 9966CC 153102204 - "blueviolet", # 8A2BE2 13843226 - "darkviolet", # 9400D3 1480211 - "darkorchid", # 9932CC 15350204 - "darkmagenta", # 8B008B 1390139 - "purple", # 800080 1280128 - "indigo", # 4B0082 750130 - "slateblue", # 6A5ACD 10690205 - "darkslateblue", # 483D8B 7261139 - "mediumslateblue", # 7B68EE 123104238 - "greenyellow", # ADFF2F 17325547 - "chartreuse", # 7FFF00 1272550 - "lawngreen", # 7CFC00 1242520 - "lime", # 00FF00 02550 - "limegreen", # 32CD32 5020550 - "palegreen", # 98FB98 152251152 - "lightgreen", # 90EE90 144238144 - "mediumspringgreen", # 00FA9A 0250154 - "springgreen", # 00FF7F 0255127 - "mediumseagreen", # 3CB371 60179113 - "seagreen", # 2E8B57 4613987 - "forestgreen", # 228B22 3413934 - "green", # 008000 01280 - "darkgreen", # 006400 01000 - "yellowgreen", # 9ACD32 15420550 - "olivedrab", # 6B8E23 10714235 - "olive", # 808000 1281280 - "darkolivegreen", # 556B2F 8510747 - "mediumaquamarine", # 66CDAA 102205170 - "darkseagreen", # 8FBC8F 143188143 - "lightseagreen", # 20B2AA 32178170 - "darkcyan", # 008B8B 0139139 - "teal", # 008080 0128128 - "aqua", # 00FFFF 0255255 - "cyan", # 00FFFF 0255255 - "lightcyan", # E0FFFF 224255255 - "paleturquoise", # AFEEEE 175238238 - "aquamarine", # 7FFFD4 127255212 - "turquoise", # 40E0D0 64224208 - "mediumturquoise", # 48D1CC 72209204 - "darkturquoise", # 00CED1 0206209 - "cadetblue", # 5F9EA0 95158160 - "steelblue", # 4682B4 70130180 - "lightsteelblue", # B0C4DE 176196222 - "powderblue", # B0E0E6 176224230 - "lightblue", # ADD8E6 173216230 - "skyblue", # 87CEEB 135206235 - "lightskyblue", # 87CEFA 135206250 - "deepskyblue", # 00BFFF 0191255 - "dodgerblue", # 1E90FF 30144255 - "cornflowerblue", # 6495ED 100149237 - "mediumslateblue", # 7B68EE 123104238 - "royalblue", # 4169E1 65105225 - "blue", # 0000FF 00255 - "mediumblue", # 0000CD 00205 - "darkblue", # 00008B 00139 - "navy", # 000080 00128 - "midnightblue", # 191970 2525112 - "cornsilk", # FFF8DC 255248220 - "blanchedalmond", # FFEBCD 255235205 - "bisque", # FFE4C4 255228196 - "navajowhite", # FFDEAD 255222173 - "wheat", # F5DEB3 245222179 - "burlywood", # DEB887 222184135 - "tan", # D2B48C 210180140 - "rosybrown", # BC8F8F 188143143 - "sandybrown", # F4A460 24416496 - "goldenrod", # DAA520 21816532 - "darkgoldenrod", # B8860B 18413411 - "peru", # CD853F 20513363 - "chocolate", # D2691E 21010530 - "saddlebrown", # 8B4513 1396919 - "sienna", # A0522D 1608245 - "brown", # A52A2A 1654242 - "maroon", # 800000 12800 - "white", # FFFFFF 255255255 - "snow", # FFFAFA 255250250 - "honeydew", # F0FFF0 240255240 - "mintcream", # F5FFFA 245255250 - "azure", # F0FFFF 240255255 - "aliceblue", # F0F8FF 240248255 - "ghostwhite", # F8F8FF 248248255 - "whitesmoke", # F5F5F5 245245245 - "seashell", # FFF5EE 255245238 - "beige", # F5F5DC 245245220 - "oldlace", # FDF5E6 253245230 - "floralwhite", # FFFAF0 255250240 - "ivory", # FFFFF0 255255240 - "antiquewhite", # FAEBD7 250235215 - "linen", # FAF0E6 250240230 - "lavenderblush", # FFF0F5 255240245 - "mistyrose", # FFE4E1 255228225 - "gainsboro", # DCDCDC 220220220 - "lightgrey", # D3D3D3 211211211 - "silver", # C0C0C0 192192192 - "darkgray", # A9A9A9 169169169 - "gray", # 808080 128128128 - "dimgray", # 696969 105105105 - "lightslategray", # 778899 119136153 - "slategray", # 708090 112128144 - "darkslategray", # 2F4F4F 477979 - "black"] ) # 000000 000 - -# http://colorbrewer2.org/ -#schemas = {'Spectral': {3: [(252, 141, 89), (255, 255, 191), (153, 213, 148)], 4: [(215, 25, 28), (253, 174, 97), (171, 221, 164), (43, 131, 186)], 5: [(215, 25, 28), (253, 174, 97), (255, 255, 191), (171, 221, 164), (43, 131, 186)], 6: [(213, 62, 79), (252, 141, 89), (254, 224, 139), (230, 245, 152), (153, 213, 148), (50, 136, 189)], 7: [(213, 62, 79), (252, 141, 89), (254, 224, 139), (255, 255, 191), (230, 245, 152), (153, 213, 148), (50, 136, 189)], 8: [(213, 62, 79), (244, 109, 67), (253, 174, 97), (254, 224, 139), (230, 245, 152), (171, 221, 164), (102, 194, 165), (50, 136, 189)], 9: [(213, 62, 79), (244, 109, 67), (253, 174, 97), (254, 224, 139), (255, 255, 191), (230, 245, 152), (171, 221, 164), (102, 194, 165), (50, 136, 189)], 10: [(158, 1, 66), (213, 62, 79), (244, 109, 67), (253, 174, 97), (254, 224, 139), (230, 245, 152), (171, 221, 164), (102, 194, 165), (50, 136, 189), (94, 79, 162)], 11: [(158, 1, 66), (213, 62, 79), (244, 109, 67), (253, 174, 97), (254, 224, 139), (255, 255, 191), (230, 245, 152), (171, 221, 164), (102, 194, 165), (50, 136, 189), (94, 79, 162)]}, 'RdYlGn': {3: [(252, 141, 89), (255, 255, 191), (145, 207, 96)], 4: [(215, 25, 28), (253, 174, 97), (166, 217, 106), (26, 150, 65)], 5: [(215, 25, 28), (253, 174, 97), (255, 255, 191), (166, 217, 106), (26, 150, 65)], 6: [(215, 48, 39), (252, 141, 89), (254, 224, 139), (217, 239, 139), (145, 207, 96), (26, 152, 80)], 7: [(215, 48, 39), (252, 141, 89), (254, 224, 139), (255, 255, 191), (217, 239, 139), (145, 207, 96), (26, 152, 80)], 8: [(215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 139), (217, 239, 139), (166, 217, 106), (102, 189, 99), (26, 152, 80)], 9: [(215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 139), (255, 255, 191), (217, 239, 139), (166, 217, 106), (102, 189, 99), (26, 152, 80)], 10: [(165, 0, 38), (215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 139), (217, 239, 139), (166, 217, 106), (102, 189, 99), (26, 152, 80), (0, 104, 55)], 11: [(165, 0, 38), (215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 139), (255, 255, 191), (217, 239, 139), (166, 217, 106), (102, 189, 99), (26, 152, 80), (0, 104, 55)]}, 'Set2': {3: [(102, 194, 165), (252, 141, 98), (141, 160, 203)], 4: [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138, 195)], 5: [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138, 195), (166, 216, 84)], 6: [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138, 195), (166, 216, 84), (255, 217, 47)], 7: [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138, 195), (166, 216, 84), (255, 217, 47), (229, 196, 148)], 8: [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138, 195), (166, 216, 84), (255, 217, 47), (229, 196, 148), (179, 179, 179)]}, 'Accent': {3: [(127, 201, 127), (190, 174, 212), (253, 192, 134)], 4: [(127, 201, 127), (190, 174, 212), (253, 192, 134), (255, 255, 153)], 5: [(127, 201, 127), (190, 174, 212), (253, 192, 134), (255, 255, 153), (56, 108, 176)], 6: [(127, 201, 127), (190, 174, 212), (253, 192, 134), (255, 255, 153), (56, 108, 176), (240, 2, 127)], 7: [(127, 201, 127), (190, 174, 212), (253, 192, 134), (255, 255, 153), (56, 108, 176), (240, 2, 127), (191, 91, 23)], 8: [(127, 201, 127), (190, 174, 212), (253, 192, 134), (255, 255, 153), (56, 108, 176), (240, 2, 127), (191, 91, 23), (102, 102, 102)]}, 'OrRd': {3: [(254, 232, 200), (253, 187, 132), (227, 74, 51)], 4: [(254, 240, 217), (253, 204, 138), (252, 141, 89), (215, 48, 31)], 5: [(254, 240, 217), (253, 204, 138), (252, 141, 89), (227, 74, 51), (179, 0, 0)], 6: [(254, 240, 217), (253, 212, 158), (253, 187, 132), (252, 141, 89), (227, 74, 51), (179, 0, 0)], 7: [(254, 240, 217), (253, 212, 158), (253, 187, 132), (252, 141, 89), (239, 101, 72), (215, 48, 31), (153, 0, 0)], 8: [(255, 247, 236), (254, 232, 200), (253, 212, 158), (253, 187, 132), (252, 141, 89), (239, 101, 72), (215, 48, 31), (153, 0, 0)], 9: [(255, 247, 236), (254, 232, 200), (253, 212, 158), (253, 187, 132), (252, 141, 89), (239, 101, 72), (215, 48, 31), (179, 0, 0), (127, 0, 0)]}, 'Set1': {3: [(228, 26, 28), (55, 126, 184), (77, 175, 74)], 4: [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163)], 5: [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163), (255, 127, 0)], 6: [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163), (255, 127, 0), (255, 255, 51)], 7: [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163), (255, 127, 0), (255, 255, 51), (166, 86, 40)], 8: [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163), (255, 127, 0), (255, 255, 51), (166, 86, 40), (247, 129, 191)], 9: [(228, 26, 28), (55, 126, 184), (77, 175, 74), (152, 78, 163), (255, 127, 0), (255, 255, 51), (166, 86, 40), (247, 129, 191), (153, 153, 153)]}, 'PuBu': {3: [(236, 231, 242), (166, 189, 219), (43, 140, 190)], 4: [(241, 238, 246), (189, 201, 225), (116, 169, 207), (5, 112, 176)], 5: [(241, 238, 246), (189, 201, 225), (116, 169, 207), (43, 140, 190), (4, 90, 141)], 6: [(241, 238, 246), (208, 209, 230), (166, 189, 219), (116, 169, 207), (43, 140, 190), (4, 90, 141)], 7: [(241, 238, 246), (208, 209, 230), (166, 189, 219), (116, 169, 207), (54, 144, 192), (5, 112, 176), (3, 78, 123)], 8: [(255, 247, 251), (236, 231, 242), (208, 209, 230), (166, 189, 219), (116, 169, 207), (54, 144, 192), (5, 112, 176), (3, 78, 123)], 9: [(255, 247, 251), (236, 231, 242), (208, 209, 230), (166, 189, 219), (116, 169, 207), (54, 144, 192), (5, 112, 176), (4, 90, 141), (2, 56, 88)]}, 'Set3': {3: [(141, 211, 199), (255, 255, 179), (190, 186, 218)], 4: [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114)], 5: [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211)], 6: [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98)], 7: [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105)], 8: [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105), (252, 205, 229)], 9: [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105), (252, 205, 229), (217, 217, 217)], 10: [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105), (252, 205, 229), (217, 217, 217), (188, 128, 189)], 11: [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105), (252, 205, 229), (217, 217, 217), (188, 128, 189), (204, 235, 197)], 12: [(141, 211, 199), (255, 255, 179), (190, 186, 218), (251, 128, 114), (128, 177, 211), (253, 180, 98), (179, 222, 105), (252, 205, 229), (217, 217, 217), (188, 128, 189), (204, 235, 197), (255, 237, 111)]}, 'BuPu': {3: [(224, 236, 244), (158, 188, 218), (136, 86, 167)], 4: [(237, 248, 251), (179, 205, 227), (140, 150, 198), (136, 65, 157)], 5: [(237, 248, 251), (179, 205, 227), (140, 150, 198), (136, 86, 167), (129, 15, 124)], 6: [(237, 248, 251), (191, 211, 230), (158, 188, 218), (140, 150, 198), (136, 86, 167), (129, 15, 124)], 7: [(237, 248, 251), (191, 211, 230), (158, 188, 218), (140, 150, 198), (140, 107, 177), (136, 65, 157), (110, 1, 107)], 8: [(247, 252, 253), (224, 236, 244), (191, 211, 230), (158, 188, 218), (140, 150, 198), (140, 107, 177), (136, 65, 157), (110, 1, 107)], 9: [(247, 252, 253), (224, 236, 244), (191, 211, 230), (158, 188, 218), (140, 150, 198), (140, 107, 177), (136, 65, 157), (129, 15, 124), (77, 0, 75)]}, 'Dark2': {3: [(27, 158, 119), (217, 95, 2), (117, 112, 179)], 4: [(27, 158, 119), (217, 95, 2), (117, 112, 179), (231, 41, 138)], 5: [(27, 158, 119), (217, 95, 2), (117, 112, 179), (231, 41, 138), (102, 166, 30)], 6: [(27, 158, 119), (217, 95, 2), (117, 112, 179), (231, 41, 138), (102, 166, 30), (230, 171, 2)], 7: [(27, 158, 119), (217, 95, 2), (117, 112, 179), (231, 41, 138), (102, 166, 30), (230, 171, 2), (166, 118, 29)], 8: [(27, 158, 119), (217, 95, 2), (117, 112, 179), (231, 41, 138), (102, 166, 30), (230, 171, 2), (166, 118, 29), (102, 102, 102)]}, 'RdBu': {3: [(239, 138, 98), (247, 247, 247), (103, 169, 207)], 4: [(202, 0, 32), (244, 165, 130), (146, 197, 222), (5, 113, 176)], 5: [(202, 0, 32), (244, 165, 130), (247, 247, 247), (146, 197, 222), (5, 113, 176)], 6: [(178, 24, 43), (239, 138, 98), (253, 219, 199), (209, 229, 240), (103, 169, 207), (33, 102, 172)], 7: [(178, 24, 43), (239, 138, 98), (253, 219, 199), (247, 247, 247), (209, 229, 240), (103, 169, 207), (33, 102, 172)], 8: [(178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (209, 229, 240), (146, 197, 222), (67, 147, 195), (33, 102, 172)], 9: [(178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (247, 247, 247), (209, 229, 240), (146, 197, 222), (67, 147, 195), (33, 102, 172)], 10: [(103, 0, 31), (178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (209, 229, 240), (146, 197, 222), (67, 147, 195), (33, 102, 172), (5, 48, 97)], 11: [(103, 0, 31), (178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (247, 247, 247), (209, 229, 240), (146, 197, 222), (67, 147, 195), (33, 102, 172), (5, 48, 97)]}, 'Oranges': {3: [(254, 230, 206), (253, 174, 107), (230, 85, 13)], 4: [(254, 237, 222), (253, 190, 133), (253, 141, 60), (217, 71, 1)], 5: [(254, 237, 222), (253, 190, 133), (253, 141, 60), (230, 85, 13), (166, 54, 3)], 6: [(254, 237, 222), (253, 208, 162), (253, 174, 107), (253, 141, 60), (230, 85, 13), (166, 54, 3)], 7: [(254, 237, 222), (253, 208, 162), (253, 174, 107), (253, 141, 60), (241, 105, 19), (217, 72, 1), (140, 45, 4)], 8: [(255, 245, 235), (254, 230, 206), (253, 208, 162), (253, 174, 107), (253, 141, 60), (241, 105, 19), (217, 72, 1), (140, 45, 4)], 9: [(255, 245, 235), (254, 230, 206), (253, 208, 162), (253, 174, 107), (253, 141, 60), (241, 105, 19), (217, 72, 1), (166, 54, 3), (127, 39, 4)]}, 'BuGn': {3: [(229, 245, 249), (153, 216, 201), (44, 162, 95)], 4: [(237, 248, 251), (178, 226, 226), (102, 194, 164), (35, 139, 69)], 5: [(237, 248, 251), (178, 226, 226), (102, 194, 164), (44, 162, 95), (0, 109, 44)], 6: [(237, 248, 251), (204, 236, 230), (153, 216, 201), (102, 194, 164), (44, 162, 95), (0, 109, 44)], 7: [(237, 248, 251), (204, 236, 230), (153, 216, 201), (102, 194, 164), (65, 174, 118), (35, 139, 69), (0, 88, 36)], 8: [(247, 252, 253), (229, 245, 249), (204, 236, 230), (153, 216, 201), (102, 194, 164), (65, 174, 118), (35, 139, 69), (0, 88, 36)], 9: [(247, 252, 253), (229, 245, 249), (204, 236, 230), (153, 216, 201), (102, 194, 164), (65, 174, 118), (35, 139, 69), (0, 109, 44), (0, 68, 27)]}, 'PiYG': {3: [(233, 163, 201), (247, 247, 247), (161, 215, 106)], 4: [(208, 28, 139), (241, 182, 218), (184, 225, 134), (77, 172, 38)], 5: [(208, 28, 139), (241, 182, 218), (247, 247, 247), (184, 225, 134), (77, 172, 38)], 6: [(197, 27, 125), (233, 163, 201), (253, 224, 239), (230, 245, 208), (161, 215, 106), (77, 146, 33)], 7: [(197, 27, 125), (233, 163, 201), (253, 224, 239), (247, 247, 247), (230, 245, 208), (161, 215, 106), (77, 146, 33)], 8: [(197, 27, 125), (222, 119, 174), (241, 182, 218), (253, 224, 239), (230, 245, 208), (184, 225, 134), (127, 188, 65), (77, 146, 33)], 9: [(197, 27, 125), (222, 119, 174), (241, 182, 218), (253, 224, 239), (247, 247, 247), (230, 245, 208), (184, 225, 134), (127, 188, 65), (77, 146, 33)], 10: [(142, 1, 82), (197, 27, 125), (222, 119, 174), (241, 182, 218), (253, 224, 239), (230, 245, 208), (184, 225, 134), (127, 188, 65), (77, 146, 33), (39, 100, 25)], 11: [(142, 1, 82), (197, 27, 125), (222, 119, 174), (241, 182, 218), (253, 224, 239), (247, 247, 247), (230, 245, 208), (184, 225, 134), (127, 188, 65), (77, 146, 33), (39, 100, 25)]}, 'YlOrBr': {3: [(255, 247, 188), (254, 196, 79), (217, 95, 14)], 4: [(255, 255, 212), (254, 217, 142), (254, 153, 41), (204, 76, 2)], 5: [(255, 255, 212), (254, 217, 142), (254, 153, 41), (217, 95, 14), (153, 52, 4)], 6: [(255, 255, 212), (254, 227, 145), (254, 196, 79), (254, 153, 41), (217, 95, 14), (153, 52, 4)], 7: [(255, 255, 212), (254, 227, 145), (254, 196, 79), (254, 153, 41), (236, 112, 20), (204, 76, 2), (140, 45, 4)], 8: [(255, 255, 229), (255, 247, 188), (254, 227, 145), (254, 196, 79), (254, 153, 41), (236, 112, 20), (204, 76, 2), (140, 45, 4)], 9: [(255, 255, 229), (255, 247, 188), (254, 227, 145), (254, 196, 79), (254, 153, 41), (236, 112, 20), (204, 76, 2), (153, 52, 4), (102, 37, 6)]}, 'YlGn': {3: [(247, 252, 185), (173, 221, 142), (49, 163, 84)], 4: [(255, 255, 204), (194, 230, 153), (120, 198, 121), (35, 132, 67)], 5: [(255, 255, 204), (194, 230, 153), (120, 198, 121), (49, 163, 84), (0, 104, 55)], 6: [(255, 255, 204), (217, 240, 163), (173, 221, 142), (120, 198, 121), (49, 163, 84), (0, 104, 55)], 7: [(255, 255, 204), (217, 240, 163), (173, 221, 142), (120, 198, 121), (65, 171, 93), (35, 132, 67), (0, 90, 50)], 8: [(255, 255, 229), (247, 252, 185), (217, 240, 163), (173, 221, 142), (120, 198, 121), (65, 171, 93), (35, 132, 67), (0, 90, 50)], 9: [(255, 255, 229), (247, 252, 185), (217, 240, 163), (173, 221, 142), (120, 198, 121), (65, 171, 93), (35, 132, 67), (0, 104, 55), (0, 69, 41)]}, 'Reds': {3: [(254, 224, 210), (252, 146, 114), (222, 45, 38)], 4: [(254, 229, 217), (252, 174, 145), (251, 106, 74), (203, 24, 29)], 5: [(254, 229, 217), (252, 174, 145), (251, 106, 74), (222, 45, 38), (165, 15, 21)], 6: [(254, 229, 217), (252, 187, 161), (252, 146, 114), (251, 106, 74), (222, 45, 38), (165, 15, 21)], 7: [(254, 229, 217), (252, 187, 161), (252, 146, 114), (251, 106, 74), (239, 59, 44), (203, 24, 29), (153, 0, 13)], 8: [(255, 245, 240), (254, 224, 210), (252, 187, 161), (252, 146, 114), (251, 106, 74), (239, 59, 44), (203, 24, 29), (153, 0, 13)], 9: [(255, 245, 240), (254, 224, 210), (252, 187, 161), (252, 146, 114), (251, 106, 74), (239, 59, 44), (203, 24, 29), (165, 15, 21), (103, 0, 13)]}, 'RdPu': {3: [(253, 224, 221), (250, 159, 181), (197, 27, 138)], 4: [(254, 235, 226), (251, 180, 185), (247, 104, 161), (174, 1, 126)], 5: [(254, 235, 226), (251, 180, 185), (247, 104, 161), (197, 27, 138), (122, 1, 119)], 6: [(254, 235, 226), (252, 197, 192), (250, 159, 181), (247, 104, 161), (197, 27, 138), (122, 1, 119)], 7: [(254, 235, 226), (252, 197, 192), (250, 159, 181), (247, 104, 161), (221, 52, 151), (174, 1, 126), (122, 1, 119)], 8: [(255, 247, 243), (253, 224, 221), (252, 197, 192), (250, 159, 181), (247, 104, 161), (221, 52, 151), (174, 1, 126), (122, 1, 119)], 9: [(255, 247, 243), (253, 224, 221), (252, 197, 192), (250, 159, 181), (247, 104, 161), (221, 52, 151), (174, 1, 126), (122, 1, 119), (73, 0, 106)]}, 'Greens': {3: [(229, 245, 224), (161, 217, 155), (49, 163, 84)], 4: [(237, 248, 233), (186, 228, 179), (116, 196, 118), (35, 139, 69)], 5: [(237, 248, 233), (186, 228, 179), (116, 196, 118), (49, 163, 84), (0, 109, 44)], 6: [(237, 248, 233), (199, 233, 192), (161, 217, 155), (116, 196, 118), (49, 163, 84), (0, 109, 44)], 7: [(237, 248, 233), (199, 233, 192), (161, 217, 155), (116, 196, 118), (65, 171, 93), (35, 139, 69), (0, 90, 50)], 8: [(247, 252, 245), (229, 245, 224), (199, 233, 192), (161, 217, 155), (116, 196, 118), (65, 171, 93), (35, 139, 69), (0, 90, 50)], 9: [(247, 252, 245), (229, 245, 224), (199, 233, 192), (161, 217, 155), (116, 196, 118), (65, 171, 93), (35, 139, 69), (0, 109, 44), (0, 68, 27)]}, 'PRGn': {3: [(175, 141, 195), (247, 247, 247), (127, 191, 123)], 4: [(123, 50, 148), (194, 165, 207), (166, 219, 160), (0, 136, 55)], 5: [(123, 50, 148), (194, 165, 207), (247, 247, 247), (166, 219, 160), (0, 136, 55)], 6: [(118, 42, 131), (175, 141, 195), (231, 212, 232), (217, 240, 211), (127, 191, 123), (27, 120, 55)], 7: [(118, 42, 131), (175, 141, 195), (231, 212, 232), (247, 247, 247), (217, 240, 211), (127, 191, 123), (27, 120, 55)], 8: [(118, 42, 131), (153, 112, 171), (194, 165, 207), (231, 212, 232), (217, 240, 211), (166, 219, 160), (90, 174, 97), (27, 120, 55)], 9: [(118, 42, 131), (153, 112, 171), (194, 165, 207), (231, 212, 232), (247, 247, 247), (217, 240, 211), (166, 219, 160), (90, 174, 97), (27, 120, 55)], 10: [(64, 0, 75), (118, 42, 131), (153, 112, 171), (194, 165, 207), (231, 212, 232), (217, 240, 211), (166, 219, 160), (90, 174, 97), (27, 120, 55), (0, 68, 27)], 11: [(64, 0, 75), (118, 42, 131), (153, 112, 171), (194, 165, 207), (231, 212, 232), (247, 247, 247), (217, 240, 211), (166, 219, 160), (90, 174, 97), (27, 120, 55), (0, 68, 27)]}, 'YlGnBu': {3: [(237, 248, 177), (127, 205, 187), (44, 127, 184)], 4: [(255, 255, 204), (161, 218, 180), (65, 182, 196), (34, 94, 168)], 5: [(255, 255, 204), (161, 218, 180), (65, 182, 196), (44, 127, 184), (37, 52, 148)], 6: [(255, 255, 204), (199, 233, 180), (127, 205, 187), (65, 182, 196), (44, 127, 184), (37, 52, 148)], 7: [(255, 255, 204), (199, 233, 180), (127, 205, 187), (65, 182, 196), (29, 145, 192), (34, 94, 168), (12, 44, 132)], 8: [(255, 255, 217), (237, 248, 177), (199, 233, 180), (127, 205, 187), (65, 182, 196), (29, 145, 192), (34, 94, 168), (12, 44, 132)], 9: [(255, 255, 217), (237, 248, 177), (199, 233, 180), (127, 205, 187), (65, 182, 196), (29, 145, 192), (34, 94, 168), (37, 52, 148), (8, 29, 88)]}, 'RdYlBu': {3: [(252, 141, 89), (255, 255, 191), (145, 191, 219)], 4: [(215, 25, 28), (253, 174, 97), (171, 217, 233), (44, 123, 182)], 5: [(215, 25, 28), (253, 174, 97), (255, 255, 191), (171, 217, 233), (44, 123, 182)], 6: [(215, 48, 39), (252, 141, 89), (254, 224, 144), (224, 243, 248), (145, 191, 219), (69, 117, 180)], 7: [(215, 48, 39), (252, 141, 89), (254, 224, 144), (255, 255, 191), (224, 243, 248), (145, 191, 219), (69, 117, 180)], 8: [(215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 144), (224, 243, 248), (171, 217, 233), (116, 173, 209), (69, 117, 180)], 9: [(215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 144), (255, 255, 191), (224, 243, 248), (171, 217, 233), (116, 173, 209), (69, 117, 180)], 10: [(165, 0, 38), (215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 144), (224, 243, 248), (171, 217, 233), (116, 173, 209), (69, 117, 180), (49, 54, 149)], 11: [(165, 0, 38), (215, 48, 39), (244, 109, 67), (253, 174, 97), (254, 224, 144), (255, 255, 191), (224, 243, 248), (171, 217, 233), (116, 173, 209), (69, 117, 180), (49, 54, 149)]}, 'Paired': {3: [(166, 206, 227), (31, 120, 180), (178, 223, 138)], 4: [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44)], 5: [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153)], 6: [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28)], 7: [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111)], 8: [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111), (255, 127, 0)], 9: [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111), (255, 127, 0), (202, 178, 214)], 10: [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111), (255, 127, 0), (202, 178, 214), (106, 61, 154)], 11: [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111), (255, 127, 0), (202, 178, 214), (106, 61, 154), (255, 255, 153)], 12: [(166, 206, 227), (31, 120, 180), (178, 223, 138), (51, 160, 44), (251, 154, 153), (227, 26, 28), (253, 191, 111), (255, 127, 0), (202, 178, 214), (106, 61, 154), (255, 255, 153), (177, 89, 40)]}, 'BrBG': {3: [(216, 179, 101), (245, 245, 245), (90, 180, 172)], 4: [(166, 97, 26), (223, 194, 125), (128, 205, 193), (1, 133, 113)], 5: [(166, 97, 26), (223, 194, 125), (245, 245, 245), (128, 205, 193), (1, 133, 113)], 6: [(140, 81, 10), (216, 179, 101), (246, 232, 195), (199, 234, 229), (90, 180, 172), (1, 102, 94)], 7: [(140, 81, 10), (216, 179, 101), (246, 232, 195), (245, 245, 245), (199, 234, 229), (90, 180, 172), (1, 102, 94)], 8: [(140, 81, 10), (191, 129, 45), (223, 194, 125), (246, 232, 195), (199, 234, 229), (128, 205, 193), (53, 151, 143), (1, 102, 94)], 9: [(140, 81, 10), (191, 129, 45), (223, 194, 125), (246, 232, 195), (245, 245, 245), (199, 234, 229), (128, 205, 193), (53, 151, 143), (1, 102, 94)], 10: [(84, 48, 5), (140, 81, 10), (191, 129, 45), (223, 194, 125), (246, 232, 195), (199, 234, 229), (128, 205, 193), (53, 151, 143), (1, 102, 94), (0, 60, 48)], 11: [(84, 48, 5), (140, 81, 10), (191, 129, 45), (223, 194, 125), (246, 232, 195), (245, 245, 245), (199, 234, 229), (128, 205, 193), (53, 151, 143), (1, 102, 94), (0, 60, 48)]}, 'Purples': {3: [(239, 237, 245), (188, 189, 220), (117, 107, 177)], 4: [(242, 240, 247), (203, 201, 226), (158, 154, 200), (106, 81, 163)], 5: [(242, 240, 247), (203, 201, 226), (158, 154, 200), (117, 107, 177), (84, 39, 143)], 6: [(242, 240, 247), (218, 218, 235), (188, 189, 220), (158, 154, 200), (117, 107, 177), (84, 39, 143)], 7: [(242, 240, 247), (218, 218, 235), (188, 189, 220), (158, 154, 200), (128, 125, 186), (106, 81, 163), (74, 20, 134)], 8: [(252, 251, 253), (239, 237, 245), (218, 218, 235), (188, 189, 220), (158, 154, 200), (128, 125, 186), (106, 81, 163), (74, 20, 134)], 9: [(252, 251, 253), (239, 237, 245), (218, 218, 235), (188, 189, 220), (158, 154, 200), (128, 125, 186), (106, 81, 163), (84, 39, 143), (63, 0, 125)]}, 'Pastel2': {3: [(179, 226, 205), (253, 205, 172), (203, 213, 232)], 4: [(179, 226, 205), (253, 205, 172), (203, 213, 232), (244, 202, 228)], 5: [(179, 226, 205), (253, 205, 172), (203, 213, 232), (244, 202, 228), (230, 245, 201)], 6: [(179, 226, 205), (253, 205, 172), (203, 213, 232), (244, 202, 228), (230, 245, 201), (255, 242, 174)], 7: [(179, 226, 205), (253, 205, 172), (203, 213, 232), (244, 202, 228), (230, 245, 201), (255, 242, 174), (241, 226, 204)], 8: [(179, 226, 205), (253, 205, 172), (203, 213, 232), (244, 202, 228), (230, 245, 201), (255, 242, 174), (241, 226, 204), (204, 204, 204)]}, 'Pastel1': {3: [(251, 180, 174), (179, 205, 227), (204, 235, 197)], 4: [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228)], 5: [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228), (254, 217, 166)], 6: [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228), (254, 217, 166), (255, 255, 204)], 7: [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228), (254, 217, 166), (255, 255, 204), (229, 216, 189)], 8: [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228), (254, 217, 166), (255, 255, 204), (229, 216, 189), (253, 218, 236)], 9: [(251, 180, 174), (179, 205, 227), (204, 235, 197), (222, 203, 228), (254, 217, 166), (255, 255, 204), (229, 216, 189), (253, 218, 236), (242, 242, 242)]}, 'GnBu': {3: [(224, 243, 219), (168, 221, 181), (67, 162, 202)], 4: [(240, 249, 232), (186, 228, 188), (123, 204, 196), (43, 140, 190)], 5: [(240, 249, 232), (186, 228, 188), (123, 204, 196), (67, 162, 202), (8, 104, 172)], 6: [(240, 249, 232), (204, 235, 197), (168, 221, 181), (123, 204, 196), (67, 162, 202), (8, 104, 172)], 7: [(240, 249, 232), (204, 235, 197), (168, 221, 181), (123, 204, 196), (78, 179, 211), (43, 140, 190), (8, 88, 158)], 8: [(247, 252, 240), (224, 243, 219), (204, 235, 197), (168, 221, 181), (123, 204, 196), (78, 179, 211), (43, 140, 190), (8, 88, 158)], 9: [(247, 252, 240), (224, 243, 219), (204, 235, 197), (168, 221, 181), (123, 204, 196), (78, 179, 211), (43, 140, 190), (8, 104, 172), (8, 64, 129)]}, 'Greys': {3: [(240, 240, 240), (189, 189, 189), (99, 99, 99)], 4: [(247, 247, 247), (204, 204, 204), (150, 150, 150), (82, 82, 82)], 5: [(247, 247, 247), (204, 204, 204), (150, 150, 150), (99, 99, 99), (37, 37, 37)], 6: [(247, 247, 247), (217, 217, 217), (189, 189, 189), (150, 150, 150), (99, 99, 99), (37, 37, 37)], 7: [(247, 247, 247), (217, 217, 217), (189, 189, 189), (150, 150, 150), (115, 115, 115), (82, 82, 82), (37, 37, 37)], 8: [(255, 255, 255), (240, 240, 240), (217, 217, 217), (189, 189, 189), (150, 150, 150), (115, 115, 115), (82, 82, 82), (37, 37, 37)], 9: [(255, 255, 255), (240, 240, 240), (217, 217, 217), (189, 189, 189), (150, 150, 150), (115, 115, 115), (82, 82, 82), (37, 37, 37), (0, 0, 0)]}, 'RdGy': {3: [(239, 138, 98), (255, 255, 255), (153, 153, 153)], 4: [(202, 0, 32), (244, 165, 130), (186, 186, 186), (64, 64, 64)], 5: [(202, 0, 32), (244, 165, 130), (255, 255, 255), (186, 186, 186), (64, 64, 64)], 6: [(178, 24, 43), (239, 138, 98), (253, 219, 199), (224, 224, 224), (153, 153, 153), (77, 77, 77)], 7: [(178, 24, 43), (239, 138, 98), (253, 219, 199), (255, 255, 255), (224, 224, 224), (153, 153, 153), (77, 77, 77)], 8: [(178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (224, 224, 224), (186, 186, 186), (135, 135, 135), (77, 77, 77)], 9: [(178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (255, 255, 255), (224, 224, 224), (186, 186, 186), (135, 135, 135), (77, 77, 77)], 10: [(103, 0, 31), (178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (224, 224, 224), (186, 186, 186), (135, 135, 135), (77, 77, 77), (26, 26, 26)], 11: [(103, 0, 31), (178, 24, 43), (214, 96, 77), (244, 165, 130), (253, 219, 199), (255, 255, 255), (224, 224, 224), (186, 186, 186), (135, 135, 135), (77, 77, 77), (26, 26, 26)]}, 'YlOrRd': {3: [(255, 237, 160), (254, 178, 76), (240, 59, 32)], 4: [(255, 255, 178), (254, 204, 92), (253, 141, 60), (227, 26, 28)], 5: [(255, 255, 178), (254, 204, 92), (253, 141, 60), (240, 59, 32), (189, 0, 38)], 6: [(255, 255, 178), (254, 217, 118), (254, 178, 76), (253, 141, 60), (240, 59, 32), (189, 0, 38)], 7: [(255, 255, 178), (254, 217, 118), (254, 178, 76), (253, 141, 60), (252, 78, 42), (227, 26, 28), (177, 0, 38)], 8: [(255, 255, 204), (255, 237, 160), (254, 217, 118), (254, 178, 76), (253, 141, 60), (252, 78, 42), (227, 26, 28), (177, 0, 38)], 9: [(255, 255, 204), (255, 237, 160), (254, 217, 118), (254, 178, 76), (253, 141, 60), (252, 78, 42), (227, 26, 28), (189, 0, 38), (128, 0, 38)]}, 'PuOr': {3: [(241, 163, 64), (247, 247, 247), (153, 142, 195)], 4: [(230, 97, 1), (253, 184, 99), (178, 171, 210), (94, 60, 153)], 5: [(230, 97, 1), (253, 184, 99), (247, 247, 247), (178, 171, 210), (94, 60, 153)], 6: [(179, 88, 6), (241, 163, 64), (254, 224, 182), (216, 218, 235), (153, 142, 195), (84, 39, 136)], 7: [(179, 88, 6), (241, 163, 64), (254, 224, 182), (247, 247, 247), (216, 218, 235), (153, 142, 195), (84, 39, 136)], 8: [(179, 88, 6), (224, 130, 20), (253, 184, 99), (254, 224, 182), (216, 218, 235), (178, 171, 210), (128, 115, 172), (84, 39, 136)], 9: [(179, 88, 6), (224, 130, 20), (253, 184, 99), (254, 224, 182), (247, 247, 247), (216, 218, 235), (178, 171, 210), (128, 115, 172), (84, 39, 136)], 10: [(127, 59, 8), (179, 88, 6), (224, 130, 20), (253, 184, 99), (254, 224, 182), (216, 218, 235), (178, 171, 210), (128, 115, 172), (84, 39, 136), (45, 0, 75)], 11: [(127, 59, 8), (179, 88, 6), (224, 130, 20), (253, 184, 99), (254, 224, 182), (247, 247, 247), (216, 218, 235), (178, 171, 210), (128, 115, 172), (84, 39, 136), (45, 0, 75)]}, 'PuRd': {3: [(231, 225, 239), (201, 148, 199), (221, 28, 119)], 4: [(241, 238, 246), (215, 181, 216), (223, 101, 176), (206, 18, 86)], 5: [(241, 238, 246), (215, 181, 216), (223, 101, 176), (221, 28, 119), (152, 0, 67)], 6: [(241, 238, 246), (212, 185, 218), (201, 148, 199), (223, 101, 176), (221, 28, 119), (152, 0, 67)], 7: [(241, 238, 246), (212, 185, 218), (201, 148, 199), (223, 101, 176), (231, 41, 138), (206, 18, 86), (145, 0, 63)], 8: [(247, 244, 249), (231, 225, 239), (212, 185, 218), (201, 148, 199), (223, 101, 176), (231, 41, 138), (206, 18, 86), (145, 0, 63)], 9: [(247, 244, 249), (231, 225, 239), (212, 185, 218), (201, 148, 199), (223, 101, 176), (231, 41, 138), (206, 18, 86), (152, 0, 67), (103, 0, 31)]}, 'Blues': {3: [(222, 235, 247), (158, 202, 225), (49, 130, 189)], 4: [(239, 243, 255), (189, 215, 231), (107, 174, 214), (33, 113, 181)], 5: [(239, 243, 255), (189, 215, 231), (107, 174, 214), (49, 130, 189), (8, 81, 156)], 6: [(239, 243, 255), (198, 219, 239), (158, 202, 225), (107, 174, 214), (49, 130, 189), (8, 81, 156)], 7: [(239, 243, 255), (198, 219, 239), (158, 202, 225), (107, 174, 214), (66, 146, 198), (33, 113, 181), (8, 69, 148)], 8: [(247, 251, 255), (222, 235, 247), (198, 219, 239), (158, 202, 225), (107, 174, 214), (66, 146, 198), (33, 113, 181), (8, 69, 148)], 9: [(247, 251, 255), (222, 235, 247), (198, 219, 239), (158, 202, 225), (107, 174, 214), (66, 146, 198), (33, 113, 181), (8, 81, 156), (8, 48, 107)]}, 'PuBuGn': {3: [(236, 226, 240), (166, 189, 219), (28, 144, 153)], 4: [(246, 239, 247), (189, 201, 225), (103, 169, 207), (2, 129, 138)], 5: [(246, 239, 247), (189, 201, 225), (103, 169, 207), (28, 144, 153), (1, 108, 89)], 6: [(246, 239, 247), (208, 209, 230), (166, 189, 219), (103, 169, 207), (28, 144, 153), (1, 108, 89)], 7: [(246, 239, 247), (208, 209, 230), (166, 189, 219), (103, 169, 207), (54, 144, 192), (2, 129, 138), (1, 100, 80)], 8: [(255, 247, 251), (236, 226, 240), (208, 209, 230), (166, 189, 219), (103, 169, 207), (54, 144, 192), (2, 129, 138), (1, 100, 80)], 9: [(255, 247, 251), (236, 226, 240), (208, 209, 230), (166, 189, 219), (103, 169, 207), (54, 144, 192), (2, 129, 138), (1, 108, 89), (1, 70, 54)]}} -COLOR_SCHEMES = {'accent': ['#7fc97f', - '#beaed4', - '#fdc086', - '#ffff99', - '#386cb0', - '#f0027f', - '#bf5b17', - '#666666'], - 'blues': ['#f7fbff', - '#deebf7', - '#c6dbef', - '#9ecae1', - '#6baed6', - '#4292c6', - '#2171b5', - '#08519c', - '#08306b'], - 'brbg': ['#543005', - '#8c510a', - '#bf812d', - '#dfc27d', - '#f6e8c3', - '#f5f5f5', - '#c7eae5', - '#80cdc1', - '#35978f', - '#01665e', - '#003c30'], - 'bugn': ['#f7fcfd', - '#e5f5f9', - '#ccece6', - '#99d8c9', - '#66c2a4', - '#41ae76', - '#238b45', - '#006d2c', - '#00441b'], - 'bupu': ['#f7fcfd', - '#e0ecf4', - '#bfd3e6', - '#9ebcda', - '#8c96c6', - '#8c6bb1', - '#88419d', - '#810f7c', - '#4d004b'], - 'dark2': ['#1b9e77', - '#d95f02', - '#7570b3', - '#e7298a', - '#66a61e', - '#e6ab02', - '#a6761d', - '#666666'], - 'gnbu': ['#f7fcf0', - '#e0f3db', - '#ccebc5', - '#a8ddb5', - '#7bccc4', - '#4eb3d3', - '#2b8cbe', - '#0868ac', - '#084081'], - 'greens': ['#f7fcf5', - '#e5f5e0', - '#c7e9c0', - '#a1d99b', - '#74c476', - '#41ab5d', - '#238b45', - '#006d2c', - '#00441b'], - 'greys': ['#ffffff', - '#f0f0f0', - '#d9d9d9', - '#bdbdbd', - '#969696', - '#737373', - '#525252', - '#252525', - '#000000'], - 'orrd': ['#fff7ec', - '#fee8c8', - '#fdd49e', - '#fdbb84', - '#fc8d59', - '#ef6548', - '#d7301f', - '#b30000', - '#7f0000'], - 'oranges': ['#fff5eb', - '#fee6ce', - '#fdd0a2', - '#fdae6b', - '#fd8d3c', - '#f16913', - '#d94801', - '#a63603', - '#7f2704'], - 'prgn': ['#40004b', - '#762a83', - '#9970ab', - '#c2a5cf', - '#e7d4e8', - '#f7f7f7', - '#d9f0d3', - '#a6dba0', - '#5aae61', - '#1b7837', - '#00441b'], - 'paired': ['#a6cee3', - '#1f78b4', - '#b2df8a', - '#33a02c', - '#fb9a99', - '#e31a1c', - '#fdbf6f', - '#ff7f00', - '#cab2d6', - '#6a3d9a', - '#ffff99', - '#b15928'], - 'pastel1': ['#fbb4ae', - '#b3cde3', - '#ccebc5', - '#decbe4', - '#fed9a6', - '#ffffcc', - '#e5d8bd', - '#fddaec', - '#f2f2f2'], - 'pastel2': ['#b3e2cd', - '#fdcdac', - '#cbd5e8', - '#f4cae4', - '#e6f5c9', - '#fff2ae', - '#f1e2cc', - '#cccccc'], - 'piyg': ['#8e0152', - '#c51b7d', - '#de77ae', - '#f1b6da', - '#fde0ef', - '#f7f7f7', - '#e6f5d0', - '#b8e186', - '#7fbc41', - '#4d9221', - '#276419'], - 'pubu': ['#fff7fb', - '#ece7f2', - '#d0d1e6', - '#a6bddb', - '#74a9cf', - '#3690c0', - '#0570b0', - '#045a8d', - '#023858'], - 'pubugn': ['#fff7fb', - '#ece2f0', - '#d0d1e6', - '#a6bddb', - '#67a9cf', - '#3690c0', - '#02818a', - '#016c59', - '#014636'], - 'puor': ['#7f3b08', - '#b35806', - '#e08214', - '#fdb863', - '#fee0b6', - '#f7f7f7', - '#d8daeb', - '#b2abd2', - '#8073ac', - '#542788', - '#2d004b'], - 'purd': ['#f7f4f9', - '#e7e1ef', - '#d4b9da', - '#c994c7', - '#df65b0', - '#e7298a', - '#ce1256', - '#980043', - '#67001f'], - 'purples': ['#fcfbfd', - '#efedf5', - '#dadaeb', - '#bcbddc', - '#9e9ac8', - '#807dba', - '#6a51a3', - '#54278f', - '#3f007d'], - 'rdbu': ['#67001f', - '#b2182b', - '#d6604d', - '#f4a582', - '#fddbc7', - '#f7f7f7', - '#d1e5f0', - '#92c5de', - '#4393c3', - '#2166ac', - '#053061'], - 'rdgy': ['#67001f', - '#b2182b', - '#d6604d', - '#f4a582', - '#fddbc7', - '#ffffff', - '#e0e0e0', - '#bababa', - '#878787', - '#4d4d4d', - '#1a1a1a'], - 'rdpu': ['#fff7f3', - '#fde0dd', - '#fcc5c0', - '#fa9fb5', - '#f768a1', - '#dd3497', - '#ae017e', - '#7a0177', - '#49006a'], - 'rdylbu': ['#a50026', - '#d73027', - '#f46d43', - '#fdae61', - '#fee090', - '#ffffbf', - '#e0f3f8', - '#abd9e9', - '#74add1', - '#4575b4', - '#313695'], - 'rdylgn': ['#a50026', - '#d73027', - '#f46d43', - '#fdae61', - '#fee08b', - '#ffffbf', - '#d9ef8b', - '#a6d96a', - '#66bd63', - '#1a9850', - '#006837'], - 'reds': ['#fff5f0', - '#fee0d2', - '#fcbba1', - '#fc9272', - '#fb6a4a', - '#ef3b2c', - '#cb181d', - '#a50f15', - '#67000d'], - 'set1': ['#e41a1c', - '#377eb8', - '#4daf4a', - '#984ea3', - '#ff7f00', - '#ffff33', - '#a65628', - '#f781bf', - '#999999'], - 'set2': ['#66c2a5', - '#fc8d62', - '#8da0cb', - '#e78ac3', - '#a6d854', - '#ffd92f', - '#e5c494', - '#b3b3b3'], - 'set3': ['#8dd3c7', - '#ffffb3', - '#bebada', - '#fb8072', - '#80b1d3', - '#fdb462', - '#b3de69', - '#fccde5', - '#d9d9d9', - '#bc80bd', - '#ccebc5', - '#ffed6f'], - 'spectral': ['#9e0142', - '#d53e4f', - '#f46d43', - '#fdae61', - '#fee08b', - '#ffffbf', - '#e6f598', - '#abdda4', - '#66c2a5', - '#3288bd', - '#5e4fa2'], - 'ylgn': ['#ffffe5', - '#f7fcb9', - '#d9f0a3', - '#addd8e', - '#78c679', - '#41ab5d', - '#238443', - '#006837', - '#004529'], - 'ylgnbu': ['#ffffd9', - '#edf8b1', - '#c7e9b4', - '#7fcdbb', - '#41b6c4', - '#1d91c0', - '#225ea8', - '#253494', - '#081d58'], - 'ylorbr': ['#ffffe5', - '#fff7bc', - '#fee391', - '#fec44f', - '#fe9929', - '#ec7014', - '#cc4c02', - '#993404', - '#662506'], - 'ylorrd': ['#ffffcc', - '#ffeda0', - '#fed976', - '#feb24c', - '#fd8d3c', - '#fc4e2a', - '#e31a1c', - '#bd0026', - '#800026']} - -def random_color(h=None, l=None, s=None): - """ returns the RGB code of a random color. Hue (h), Lightness (l) - and Saturation (s) of the generated color could be fixed using the - pertinent function argument. """ - def rgb2hex(rgb): - return '#%02x%02x%02x' % rgb - def hls2hex(h, l, s): - return rgb2hex( tuple(map(lambda x: int(x*255), colorsys.hls_to_rgb(h, l, s)))) - - if not h: - h = random.random() - if not s: - s = 0.5 - if not l: - l = 0.5 - return hls2hex(h, l, s) diff --git a/ete2/treeview/svg_colors.pyc b/ete2/treeview/svg_colors.pyc deleted file mode 100644 index 4dc2431..0000000 Binary files a/ete2/treeview/svg_colors.pyc and /dev/null differ diff --git a/ete2/treeview/templates.py b/ete2/treeview/templates.py deleted file mode 100644 index c0e9aad..0000000 --- a/ete2/treeview/templates.py +++ /dev/null @@ -1,72 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -from ete2 import PhyloTree, PhyloNode, ClusterTree, ClusterNode, EvolTree, EvolNode -import layouts - -def apply_template(tree_style, template): - for k, v in template.iteritems(): - setattr(tree_style, k, v) - -phylogeny = { - "layout_fn": layouts.phylogeny, - "show_leaf_name":False, - "draw_guiding_lines":False - } - -evol = { - "layout_fn": layouts.evol_layout, - "show_leaf_name":True, - "draw_guiding_lines":False - } - -clustering = { - "layout_fn": layouts.large, - "show_leaf_name":False - } - -_DEFAULT_STYLE={ - PhyloTree: phylogeny, - PhyloNode: phylogeny, - EvolTree: evol, - EvolNode: evol, - ClusterTree: clustering, - ClusterNode: clustering, - } diff --git a/ete2/treeview/templates.pyc b/ete2/treeview/templates.pyc deleted file mode 100644 index 0d84d6d..0000000 Binary files a/ete2/treeview/templates.pyc and /dev/null differ diff --git a/ete2/webplugin/__init__.py b/ete2/webplugin/__init__.py deleted file mode 100644 index a220a54..0000000 --- a/ete2/webplugin/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# diff --git a/ete2/webplugin/__init__.pyc b/ete2/webplugin/__init__.pyc deleted file mode 100644 index 4c74457..0000000 Binary files a/ete2/webplugin/__init__.pyc and /dev/null differ diff --git a/ete2/webplugin/webapp.py b/ete2/webplugin/webapp.py deleted file mode 100755 index b943a4c..0000000 --- a/ete2/webplugin/webapp.py +++ /dev/null @@ -1,323 +0,0 @@ -# -*- coding: utf-8 -*- -# #START_LICENSE########################################################### -# -# -# This file is part of the Environment for Tree Exploration program -# (ETE). http://ete.cgenomics.org -# -# ETE is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# ETE is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -# License for more details. -# -# You should have received a copy of the GNU General Public License -# along with ETE. If not, see . -# -# -# ABOUT THE ETE PACKAGE -# ===================== -# -# ETE is distributed under the GPL copyleft license (2008-2011). -# -# If you make use of ETE in published work, please cite: -# -# Jaime Huerta-Cepas, Joaquin Dopazo and Toni Gabaldon. -# ETE: a python Environment for Tree Exploration. Jaime BMC -# Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 -# -# Note that extra references to the specific methods implemented in -# the toolkit are available in the documentation. -# -# More info at http://ete.cgenomics.org -# -# -# #END_LICENSE############################################################# -__VERSION__="ete2-2.2rev1026" -import sys -import os -import time -import cgi -from hashlib import md5 - -ALL = ["WebTreeApplication"] - -class WebTreeApplication(object): - """ Provides a basic WSGI application object which can handle ETE - tree visualization and interactions. Please, see the - webplugin example provided with the ETE installation package - (http://pypi.python.org/pypi/ete2).""" - - def __init__(self): - # Redirects normal output msgs to stderr, since stdout in web - # application is for the browser - sys.stdout = sys.stderr - - self.TreeConstructor = None - self.NODE_TARGET_ACTIONS = ["node", "face"] - self.TREE_TARGET_ACTIONS = ["layout", "search"] - self.actions = [] - self._layout = None - self._tree_style = None - self._width = None - self._height = None - self._size_units = "px" - self._custom_tree_renderer = None - self._treeid2layout = {} - self._external_app_handler = None - self._treeid2tree = {} - self._treeid2index = {} - self.queries = {} - self.CONFIG = { - "temp_dir":"/var/www/webplugin/", - "temp_url":"http://localhost/webplugin/tmp", - "DISPLAY" :":0" # Used by ete to render images - } - - def set_tree_size(self, w, h, units="px"): - """ Fix the size of tree image """ - self._width = w - self._height = h - self._size_units = units - - def set_external_app_handler(self, handler): - """ Sets a custom function that will extend current WSGI - application.""" - self._external_app_handler = handler - - def set_external_tree_renderer(self, handler): - """ If the tree needs to be processed every time is going to - be drawn, the task can be delegated. """ - self._custom_tree_renderer = handler - - def register_action(self, name, target, handler, checker, html_generator): - """ Adds a new web interactive function associated to tree - nodes. """ - self.actions.append([name, target, handler, checker, html_generator]) - - def set_tree_loader(self, TreeConstructor): - """ Delegate tree constructor. It allows to customize the Tree - class used to create new tree instances. """ - self._tree = TreeConstructor - - def set_default_layout_fn(self, layout_fn): - """ Fix the layout function used to render the tree. """ - self._layout = layout_fn - - def set_tree_style(self, handler): - """ Fix a :class:`TreeStyle` instance to render tree images. """ - self._tree_style = handler - - def _get_html_map(self, img_map, treeid, mapid, tree): - # Scans for node-enabled actions. - nid2actions = {} - nid2face_actions = {} - for n in tree.traverse(): - for aindex, (action, target, handler, checker, html_generator) in enumerate(self.actions): - if target == "node" and (not checker or checker(n)): - nid2actions.setdefault(int(n._nid), []).append(aindex) - elif target == "face" and (not checker or checker(n)): - nid2face_actions.setdefault(int(n._nid), []).append(aindex) - - html_map = '' %(mapid) - if img_map["nodes"]: - for x1, y1, x2, y2, nodeid, text in img_map["nodes"]: - html_map += """ """ %\ - (int(x1), int(y1), int(x2), int(y2), treeid, nodeid, ','.join(map(str, nid2actions.get(nodeid,[]))), str(nodeid) ) - if img_map["faces"]: - for x1, y1, x2, y2, nodeid, text in img_map["faces"]: - html_map += """ """ %\ - (int(x1),int(y1),int(x2),int(y2), treeid, nodeid, ','.join(map(str, nid2actions.get(nodeid,[])+nid2face_actions.get(nodeid,[]) )), text, text) - html_map += '' - return html_map - - def _load_tree(self, treeid, tree=None): - # if a tree is given, it overwrites previous versions - if tree: - t = self._tree(tree) - self._treeid2tree[treeid] = t - self._load_tree_index(treeid) - - # if no tree is given, and not in memmory, it tries to loaded - # from previous sessions - if treeid not in self._treeid2tree: - self._load_tree_from_path(treeid) - - # Returns True if tree and indexes are loaded - return (treeid in self._treeid2tree) and (treeid in self._treeid2index) - - def _load_tree_from_path(self, treeid): - tree_path = os.path.join(self.CONFIG["temp_dir"], treeid+".nw") - if os.path.exists(tree_path): - t = self._treeid2tree[treeid] = self._tree(tree_path) - self._load_tree_index(treeid) - return True - else: - return False - - def _load_tree_index(self, treeid): - if not self._treeid2index.get(treeid, {}): - tree_index = self._treeid2index[treeid] = {} - t = self._treeid2tree[treeid] - for n in t.traverse(): - if hasattr(n, "_nid"): - tree_index[str(n._nid)] = n - return True - else: - return False - - def _dump_tree_to_file(self, t, treeid): - tree_path = os.path.join(self.CONFIG["temp_dir"], treeid+".nw") - open(tree_path, "w").write(t.write(features=[])) - - def _get_tree_img(self, treeid, pre_drawing_action=None): - img_url = os.path.join(self.CONFIG["temp_url"], treeid+".png?"+str(time.time())) - img_path = os.path.join(self.CONFIG["temp_dir"], treeid+".png") - - t = self._treeid2tree[treeid] - tree_index = self._treeid2index[treeid] - - if pre_drawing_action: - atype, handler, arguments = pre_drawing_action - if atype in set(["node", "face"]) and len(arguments)==1 and handler: - nid = arguments[0] - node = tree_index.get(str(nid), None) - handler(node) - elif atype == "tree": - handler(t, arguments[0]) - elif atype == "search": - handler(t, arguments[0]) - elif atype == "layout": - self._treeid2layout[treeid] = handler - - layout_fn = self._treeid2layout.get(treeid, self._layout) - mapid = "img_map_"+str(time.time()) - img_map = _render_tree(t, img_path, self.CONFIG["DISPLAY"], layout = layout_fn, - tree_style = self._tree_style, - w=self._width, - h=self._height, - units=self._size_units) - html_map = self._get_html_map(img_map, treeid, mapid, t) - for n in t.traverse(): - self._treeid2index[treeid][str(n._nid)]=n - if hasattr(n, "_QtItem_"): - n._QtItem_ = None - delattr(n, "_QtItem_") - - tree_actions = [] - for aindex, (action, target, handler, checker, html_generator) in enumerate(self.actions): - if target in self.TREE_TARGET_ACTIONS and (not checker or checker(t)): - tree_actions.append(aindex) - - try: - version_tag = __VERSION__ - except NameError: - version_tag = "ete2" - - self._dump_tree_to_file(t, treeid) - - ete_publi = '' %\ - (version_tag) - img_html = """""" %\ - (img_url, mapid, treeid, ','.join(map(str, tree_actions))) - - tree_div_id = "ETE_tree_"+str(treeid) - return html_map+ '
'%tree_div_id + img_html + ete_publi + "
" - - # WSGI web application - def __call__(self, environ, start_response): - """ This function is executed when the application is called - by the WSGI apache module. It is, therefore, in charge of - answering web requests.""" - path = environ['PATH_INFO'].split("/") - start_response('202 OK', [('content-type', 'text/plain')]) - if environ['REQUEST_METHOD'].upper() == 'GET' and environ['QUERY_STRING']: - self.queries = cgi.parse_qs(environ['QUERY_STRING']) - elif environ['REQUEST_METHOD'].upper() == 'POST' and environ['wsgi.input']: - self.queries = cgi.parse_qs(environ['wsgi.input'].read()) - else: - self.queries = {} - - method = path[1] - treeid = self.queries.get("treeid", [None])[0] - nodeid = self.queries.get("nid", [None])[0] - textface = self.queries.get("textface", [None])[0] - actions = self.queries.get("show_actions", [None])[0] - tree = self.queries.get("tree", [None])[0] - search_term = self.queries.get("search_term", [None])[0] - aindex = self.queries.get("aindex", [None])[0] - - if method == "draw": - # if not treeid is given, generate one - if not treeid: - treeid = md5(str(time.time())).hexdigest() - - if not self._load_tree(treeid, tree): - return "draw: Cannot load the tree: %s" %treeid - - if self._custom_tree_renderer: - t = self._treeid2tree[treeid] - return self._custom_tree_renderer(t, treeid, self) - elif t and treeid: - return self._get_tree_img(treeid=treeid) - else: - return "No tree to draw" - - elif method == "get_menu": - if not self._load_tree(treeid): - return "get_menu: Cannot load the tree: %s" %treeid - - if nodeid: - tree_index = self._treeid2index[treeid] - node = tree_index[nodeid] - else: - node = None - - if textface: - header = str(textface).strip() - else: - header = "Menu" - html = """
%s
    """ %\ - (header) - for i in map(int, actions.split(",")): - aname, target, handler, checker, html_generator = self.actions[i] - if html_generator: - html += html_generator(i, treeid, nodeid, textface, node) - else: - html += """
  • %s
  • """ %\ - (treeid, nodeid, i, aname) - html += '
' - return html - - elif method == "action": - if not self._load_tree(treeid): - return "action: Cannot load the tree: %s" %treeid - - if aindex is None: - # just refresh tree - return self._get_tree_img(treeid=treeid) - else: - aname, target, handler, checker, html_generator = self.actions[int(aindex)] - - if target in set(["node", "face", "layout"]): - return self._get_tree_img(treeid=treeid, pre_drawing_action=[target, handler, [nodeid]]) - elif target in set(["search"]): - return self._get_tree_img(treeid=treeid, pre_drawing_action=[target, handler, [search_term]]) - elif target in set(["refresh"]): - return self._get_tree_img(treeid=treeid) - return "Bad guy" - - elif self._external_app_handler: - return self._external_app_handler(environ, start_response, self.queries) - else: - return '\n'.join(map(str, environ.items())) + str(self.queries) + '\t\n'.join(environ['wsgi.input']) - -def _render_tree(t, img_path, display, layout=None, tree_style=None, - w=None, h=None, units="px"): - os.environ["DISPLAY"]=display - return t.render(img_path, layout = layout, tree_style=tree_style, - w=w, h=h, units=units) diff --git a/ete2/webplugin/webapp.pyc b/ete2/webplugin/webapp.pyc deleted file mode 100644 index 55a4c12..0000000 Binary files a/ete2/webplugin/webapp.pyc and /dev/null differ diff --git a/nexus/bin/nexus_anonymise.py b/nexus/bin/nexus_anonymise.py index d1000e0..e3a1bc3 100755 --- a/nexus/bin/nexus_anonymise.py +++ b/nexus/bin/nexus_anonymise.py @@ -44,8 +44,8 @@ def hash(salt, taxon): try: nexusname = args[0] except IndexError: - print __doc__ - print "Author: %s\n" % __author__ + print(__doc__) + print("Author: %s\n" % __author__) parser.print_help() sys.exit() @@ -59,6 +59,6 @@ def hash(salt, taxon): if newnexus is not None: nexus.write_to_file(newnexus) - print "New nexus written to %s" % newnexus + print("New nexus written to %s" % newnexus) else: - print nexus.write_to_file(hash('filename', filename)) \ No newline at end of file + print(nexus.write_to_file(hash('filename', filename))) diff --git a/nexus/bin/nexus_binary2multistate.py b/nexus/bin/nexus_binary2multistate.py index 5d0eb49..ab5b273 100755 --- a/nexus/bin/nexus_binary2multistate.py +++ b/nexus/bin/nexus_binary2multistate.py @@ -18,7 +18,7 @@ options, nexuslist = parser.parse_args() if len(nexuslist) < 1: - print __doc__ + print(__doc__) parser.print_help() sys.exit() @@ -36,4 +36,4 @@ out = combine_nexuses(nexuslist2) out.write_to_file(outfile, charblock=True, interleave=False) - print("Written to %s" % outfile) \ No newline at end of file + print("Written to %s" % outfile) diff --git a/nexus/bin/nexus_combine_nexus.py b/nexus/bin/nexus_combine_nexus.py index 6022743..f665b11 100755 --- a/nexus/bin/nexus_combine_nexus.py +++ b/nexus/bin/nexus_combine_nexus.py @@ -16,11 +16,11 @@ options, nexuslist = parser.parse_args() if len(nexuslist) <= 1: - print __doc__ + print(__doc__) parser.print_help() sys.exit() nexuslist = [NexusReader(n) for n in nexuslist] out = combine_nexuses(nexuslist) out.write_to_file('combined.nex', charblock=False, interleave=False) - print("Written to combined.nex") \ No newline at end of file + print("Written to combined.nex") diff --git a/nexus/bin/nexus_deinterleave.py b/nexus/bin/nexus_deinterleave.py index cf7056e..934b31b 100755 --- a/nexus/bin/nexus_deinterleave.py +++ b/nexus/bin/nexus_deinterleave.py @@ -15,8 +15,8 @@ try: nexusname = args[0] except IndexError: - print __doc__ - print "Author: %s\n" % __author__ + print(__doc__) + print("Author: %s\n" % __author__) parser.print_help() sys.exit() @@ -29,6 +29,6 @@ if newnexus is not None: nexus.write_to_file(newnexus) - print "New nexus written to %s" % newnexus + print("New nexus written to %s" % newnexus) else: - print nexus.write() \ No newline at end of file + print(nexus.write()) diff --git a/nexus/bin/nexus_describecharacter.py b/nexus/bin/nexus_describecharacter.py index 4a3266f..9ae85ee 100755 --- a/nexus/bin/nexus_describecharacter.py +++ b/nexus/bin/nexus_describecharacter.py @@ -52,12 +52,11 @@ def print_character_stats(nexus_obj, character_index): states[state].append(taxon) for state in sorted(states): - print 'State: %s (%d / %d = %0.2f)' % (state, + print( 'State: %s (%d / %d = %0.2f)' % (state, len(states[state]), nexus_obj.data.ntaxa, (len(states[state]) / nexus_obj.data.ntaxa * 100) - ) - print "\n".join(wrapper.wrap(", ".join(states[state]))) - print + )) + print("\n".join(wrapper.wrap(", ".join(states[state])))) return @@ -75,4 +74,4 @@ def print_character_stats(nexus_obj, character_index): parser.print_help() sys.exit() - print_character_stats(NexusReader(nexusname), char) \ No newline at end of file + print_character_stats(NexusReader(nexusname), char) diff --git a/nexus/bin/nexus_describetaxa.py b/nexus/bin/nexus_describetaxa.py index 3719505..68fd2ef 100755 --- a/nexus/bin/nexus_describetaxa.py +++ b/nexus/bin/nexus_describetaxa.py @@ -25,7 +25,7 @@ def print_taxa_stats(nexus_obj): tally[site] = tally.get(site, 0) + 1 tally = ", ".join(['%s x %s' % (k,tally[k]) for k in sorted(tally)]) - print taxon.ljust(20), tally + print(taxon.ljust(20), tally) return if __name__ == '__main__': @@ -41,9 +41,9 @@ def print_taxa_stats(nexus_obj): sys.exit() n = NexusReader(nexusname) - print n + print(n) for k, v in n.blocks.items(): - print ' ', k, v + print(' ', k, v) if k == 'data': print_taxa_stats(n) diff --git a/nexus/bin/nexus_multistate2binary.py b/nexus/bin/nexus_multistate2binary.py index c8d39f8..16cc2a5 100755 --- a/nexus/bin/nexus_multistate2binary.py +++ b/nexus/bin/nexus_multistate2binary.py @@ -22,8 +22,8 @@ nexusname = args[0] newnexusname = args[1] except IndexError: - print __doc__ - print "Author: %s\n" % __author__ + print(__doc__) + print("Author: %s\n" % __author__) parser.print_help() sys.exit() diff --git a/nexus/bin/nexus_nexusmanip.py b/nexus/bin/nexus_nexusmanip.py index 4b1de35..1cae15c 100755 --- a/nexus/bin/nexus_nexusmanip.py +++ b/nexus/bin/nexus_nexusmanip.py @@ -51,11 +51,11 @@ def print_character_stats(nexus_obj): c = characters[i] tally[c] = tally.get(c, 0) + 1 - print "%5d" % i, + print("%5d" % i) for state in tally: - print "%sx%d" % (state, tally[state]), - state_distrib.append(tally[state]) - print + print("%sx%d" % (state, tally[state]), + state_distrib.append(tally[state])) + return state_distrib @@ -82,8 +82,8 @@ def print_character_stats(nexus_obj): try: nexusname = args[0] except IndexError: - print __doc__ - print "Author: %s\n" % __author__ + print(__doc__) + print("Author: %s\n" % __author__) parser.print_help() sys.exit() diff --git a/nexus/bin/nexus_randomise.py b/nexus/bin/nexus_randomise.py index 2129c95..2ec2872 100755 --- a/nexus/bin/nexus_randomise.py +++ b/nexus/bin/nexus_randomise.py @@ -22,8 +22,8 @@ try: nexusname = args[0] except IndexError: - print __doc__ - print "Author: %s\n" % __author__ + print(__doc__) + print("Author: %s\n" % __author__) parser.print_help() sys.exit() @@ -36,14 +36,14 @@ try: options.numchars = int(options.numchars) except ValueError: - print "numchars needs to be a number!" + print("numchars needs to be a number!") raise nexus = NexusReader(nexusname) nexus = shufflenexus(nexus, options.numchars) if newnexus is not None: nexus.write_to_file(newnexus) - print "New random nexus written to %s" % newnexus + print("New random nexus written to %s" % newnexus) else: - print nexus.write() - \ No newline at end of file + print(nexus.write()) + diff --git a/nexus/bin/nexus_tally.py b/nexus/bin/nexus_tally.py index f22de88..866d026 100755 --- a/nexus/bin/nexus_tally.py +++ b/nexus/bin/nexus_tally.py @@ -15,13 +15,12 @@ def print_tally(tally): wrapper = TextWrapper(initial_indent=" ", subsequent_indent="\t", width=65) for tkey in sorted(tally): - print tkey + print(tkey) for skey in sorted(tally[tkey]): s = " ".join(sorted(tally[tkey][skey])) - print " - %s: " % skey, + print(" - %s: " % skey) for w in wrapper.wrap(s): - print w - print + print(w) return @@ -31,7 +30,7 @@ def print_tally(tally): options, commands = parser.parse_args() if len(commands) != 2: - print __doc__ + print(__doc__) parser.print_help() quit() @@ -49,4 +48,4 @@ def print_tally(tally): else: quit("Invalid tally command. Only 'taxa' and 'site' are valid.") - print_tally(tally) \ No newline at end of file + print_tally(tally) diff --git a/nexus/bin/nexus_to_fasta.py b/nexus/bin/nexus_to_fasta.py index 1a90a4f..d4ecf13 100755 --- a/nexus/bin/nexus_to_fasta.py +++ b/nexus/bin/nexus_to_fasta.py @@ -22,7 +22,7 @@ n = NexusReader(nexusname) for taxon in sorted(n.data.matrix): - print '>%s' % taxon + print('>%s' % taxon) for line in wrap("".join(n.data.matrix[taxon]), 70): - print line - \ No newline at end of file + print(line) + diff --git a/nexus/bin/nexus_treemanip.py b/nexus/bin/nexus_treemanip.py index c4b48da..e203e8d 100755 --- a/nexus/bin/nexus_treemanip.py +++ b/nexus/bin/nexus_treemanip.py @@ -270,9 +270,9 @@ def run_random(num_trees, nexus_obj, do_print=False): try: nexusname = args[0] except IndexError: - print __doc__ - print __usage__ - print "Author: %s\n" % __author__ + print(__doc__) + print(__usage__) + print("Author: %s\n" % __author__) parser.print_help() sys.exit() @@ -287,8 +287,8 @@ def run_random(num_trees, nexus_obj, do_print=False): if nexus.trees.ntrees == 0: sys.exit("No trees found in found %s!" % nexusname) if options.quiet is False: - print "%d trees found with %d translated taxa" % \ - (nexus.trees.ntrees, len(nexus.trees.translators)) + print( "%d trees found with %d translated taxa" % \ + (nexus.trees.ntrees, len(nexus.trees.translators))) # Delete trees if options.deltree: @@ -313,7 +313,7 @@ def run_random(num_trees, nexus_obj, do_print=False): if newnexus is not None: nexus.write_to_file(newnexus) if options.quiet is False: - print "New nexus with %d trees written to %s" % (nexus.trees.ntrees, newnexus) + print("New nexus with %d trees written to %s" % (nexus.trees.ntrees, newnexus)) else: - print nexus.write() + print(nexus.write()) diff --git a/requirements.txt b/requirements.txt index 4e7ec6b..de39f1f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,5 +5,4 @@ six pytest matplotlib lxml -MySQL-python PyQt5