import uuid
import re

from .._compat import iteritems, integer_types
from .regex import REGEX_NOPASSWD, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType

PLURALIZE_RULES = [
    (re.compile('child$'), re.compile('child$'), 'children'),
    (re.compile('oot$'), re.compile('oot$'), 'eet'),
    (re.compile('ooth$'), re.compile('ooth$'), 'eeth'),
    (re.compile('l[eo]af$'), re.compile('l([eo])af$'), 'l\\1aves'),
    (re.compile('sis$'), re.compile('sis$'), 'ses'),
    (re.compile('man$'), re.compile('man$'), 'men'),
    (re.compile('ife$'), re.compile('ife$'), 'ives'),
    (re.compile('eau$'), re.compile('eau$'), 'eaux'),
    (re.compile('lf$'), re.compile('lf$'), 'lves'),
    (re.compile('[sxz]$'), re.compile('$'), 'es'),
    (re.compile('[^aeioudgkprt]h$'), re.compile('$'), 'es'),
    (re.compile('(qu|[^aeiou])y$'), re.compile('y$'), 'ies'),
    (re.compile('$'), re.compile('$'), 's'),
    ]

def pluralize(singular, rules=PLURALIZE_RULES):
    for line in rules:
        re_search, re_sub, replace = line
        plural = re_search.search(singular) and re_sub.sub(replace, singular)
        if plural: return plural

def hide_password(uri):
    if isinstance(uri, (list, tuple)):
        return [hide_password(item) for item in uri]
    return REGEX_NOPASSWD.sub('******', uri)

def cleanup(text):
    """
    Validates that the given text is clean: only contains [0-9a-zA-Z_]
    """

def list_represent(values, row=None):
    return ', '.join(str(v) for v in (values or []))

def xorify(orderby):
    if not orderby:
        return None
    orderby2 = orderby[0]
    for item in orderby[1:]:
        orderby2 = orderby2 | item
    return orderby2

def use_common_filters(query):
    return (query and hasattr(query, 'ignore_common_filters') and \
            not query.ignore_common_filters)

def bar_escape(item):
    return str(item).replace('|', '||')

def bar_encode(items):
    return '|%s|' % '|'.join(bar_escape(item) for item in items if str(item).strip())

def bar_decode_integer(value):
    long = integer_types[-1]
    if not hasattr(value, 'split') and hasattr(value, 'read'):
        value = value.read()
    return [long(x) for x in value.split('|') if x.strip()]

def bar_decode_string(value):
    return [x.replace('||', '|') for x in
            REGEX_UNPACK.split(value[1:-1]) if x.strip()]

def archive_record(qset, fs, archive_table, current_record):
    tablenames = qset.db._adapter.tables(qset.query)
    if len(tablenames) != 1:
        raise RuntimeError("cannot update join")
    for row in qset.select():
        fields = archive_table._filter_fields(row)
        for k, v in iteritems(fs):
            if fields[k] != v:
                fields[current_record] = row.id
                archive_table.insert(**fields)
                break
    return False

def smart_query(fields, text):
    from ..objects import Field, Table
    if not isinstance(fields, (list, tuple)):
        fields = [fields]
    new_fields = []
    for field in fields:
        if isinstance(field, Field):
            new_fields.append(field)
        elif isinstance(field, Table):
            for ofield in field:
                new_fields.append(ofield)
        else:
            raise RuntimeError("fields must be a list of fields")
    fields = new_fields
    field_map = {}
    for field in fields:
        n = field.name.lower()
        if not n in field_map:
            field_map[n] = field
        n = str(field).lower()
        if not n in field_map:
            field_map[n] = field
    constants = {}
    i = 0
    while True:
        m = REGEX_CONST_STRING.search(text)
        if not m: break
        text = text[:m.start()]+('#%i' % i)+text[m.end():]
        constants[str(i)] = m.group()[1:-1]
        i += 1
    text = re.sub('\s+', ' ', text).lower()
    for a, b in [('&', 'and'),
                 ('|', 'or'),
                 ('~', 'not'),
                 ('==', '='),
                 ('<', '<'),
                 ('>', '>'),
                 ('<=', '<='),
                 ('>=', '>='),
                 ('<>', '!='),
                 ('=<', '<='),
                 ('=>', '>='),
                 ('=', '='),
                 (' less or equal than ', '<='),
                 (' greater or equal than ', '>='),
                 (' equal or less than ', '<='),
                 (' equal or greater than ', '>='),
                 (' less or equal ', '<='),
                 (' greater or equal ', '>='),
                 (' equal or less ', '<='),
                 (' equal or greater ', '>='),
                 (' not equal to ', '!='),
                 (' not equal ', '!='),
                 (' equal to ', '='),
                 (' equal ', '='),
                 (' equals ', '='),
                 (' less than ', '<'),
                 (' greater than ', '>'),
                 (' starts with ', 'startswith'),
                 (' ends with ', 'endswith'),
                 (' not in ', 'notbelongs'),
                 (' in ', 'belongs'),
                 (' is ', '=')]:
        if a[0] == ' ':
            text = text.replace(' is'+a, ' %s ' % b)
        text = text.replace(a, ' %s ' % b)
    text = re.sub('\s+', ' ', text).lower()
    text = re.sub('(?P<a>[\<\>\!\=])\s+(?P<b>[\<\>\!\=])', '\g<a>\g<b>', text)
    query = field = neg = op = logic = None
    for item in text.split():
        if field is None:
            if item == 'not':
                neg = True
            elif not neg and not logic and item in ('and', 'or'):
                logic = item
            elif item in field_map:
                field = field_map[item]
            else:
                raise RuntimeError("Invalid syntax")
        elif not field is None and op is None:
            op = item
        elif not op is None:
            if item.startswith('#'):
                if not item[1:] in constants:
                    raise RuntimeError("Invalid syntax")
                value = constants[item[1:]]
            else:
                value = item
                if field.type in ('text', 'string', 'json'):
                    if op == '=': op = 'like'
            if op == '=': new_query = field == value
            elif op == '<': new_query = field < value
            elif op == '>': new_query = field > value
            elif op == '<=': new_query = field <= value
            elif op == '>=': new_query = field >= value
            elif op == '!=': new_query = field != value
            elif op == 'belongs': new_query = field.belongs(value.split(','))
            elif op == 'notbelongs': new_query = ~field.belongs(value.split(','))
            elif field.type == 'list:string':
                if op == 'contains': new_query = field.contains(value)
                else: raise RuntimeError("Invalid operation")
            elif field.type in ('text', 'string', 'json', 'upload'):
                if op == 'contains': new_query = field.contains(value)
                elif op == 'like': new_query = field.ilike(value)
                elif op == 'startswith': new_query = field.startswith(value)
                elif op == 'endswith': new_query = field.endswith(value)
                else: raise RuntimeError("Invalid operation")
            elif field._db._adapter.dbengine=='google:datastore' and \
                 field.type in ('list:integer', 'list:string', 'list:reference'):
                if op == 'contains': new_query = field.contains(value)
                else: raise RuntimeError("Invalid operation")
            else: raise RuntimeError("Invalid operation")
            if neg: new_query = ~new_query
            if query is None:
                query = new_query
            elif logic == 'and':
                query &= new_query
            elif logic == 'or':
                query |= new_query
            field = op = neg = logic = None
    return query

def auto_validators(field):
    db = field.db
    field_type = field.type
    #: don't apply default validation on custom types
    if isinstance(field_type, SQLCustomType):
        if hasattr(field_type, 'validator'):
            return field_type.validator
        else:
            field_type = field_type.type
    elif not isinstance(field_type, str):
        return []
    #: if a custom method is provided, call it
    if callable(db.validators_method):
        return db.validators_method(field)
    #: apply validators from validators dict if present
    if not db.validators or not isinstance(db.validators, dict):
        return []
    field_validators = db.validators.get(field_type, [])
    if not isinstance(field_validators, (list, tuple)):
        field_validators = [field_validators]
    return field_validators

def _fieldformat(r, id):
    row = r(id)
    if not row:
        return str(id)
    elif hasattr(r, '_format') and isinstance(r._format, str):
        return r._format % row
    elif hasattr(r, '_format') and callable(r._format):
        return r._format(row)
    else:
        return str(id)

class _repr_ref(object):
    def __init__(self, ref=None):
        self.ref = ref

    def __call__(self, value, row=None):
        return value if value is None else _fieldformat(self.ref, value)

class _repr_ref_list(_repr_ref):
    def __call__(self, value, row=None):
        if not value:
            return None
        refs = None
        db, id = self.ref._db, self.ref._id
        if db._adapter.dbengine == 'google:datastore':
            def count(values):
                return db(id.belongs(values)).select(id)
            rx = range(0, len(value), 30)
            refs = reduce(lambda a, b: a & b, [count(value[i:i+30])
                          for i in rx])
        else:
            refs = db(id.belongs(value)).select(id)
        return refs and ', '.join(
            _fieldformat(self.ref, x) for x in value) or ''

def auto_represent(field):
    if field.represent:
        return field.represent
    if field.db and field.type.startswith('reference') and \
            field.type.find('.') < 0 and field.type[10:] in field.db.tables:
        referenced = field.db[field.type[10:]]
        return _repr_ref(referenced)
    elif field.db and field.type.startswith('list:reference') and \
            field.type.find('.') < 0 and field.type[15:] in field.db.tables:
        referenced = field.db[field.type[15:]]
        return _repr_ref_list(referenced)
    return field.represent

def varquote_aux(name, quotestr='%s'):
    return name if REGEX_W.match(name) else quotestr % name

def uuid2int(uuidv):
    return uuid.UUID(uuidv).int

def int2uuid(n):
    return str(uuid.UUID(int=n))

# Geodal utils
def geoPoint(x, y):
    return "POINT (%f %f)" % (x, y)

def geoLine(*line):
    return "LINESTRING (%s)" % ','.join("%f %f" % item for item in line)

def geoPolygon(*line):
    return "POLYGON ((%s))" % ','.join("%f %f" % item for item in line)


while True:
        m = REGEX_CONST_STRING.search(text)
        if not m: break
        text = text[:m.start()]+('#%i' % i)+text[m.end():]
        constants[str(i)] = m.group()[1:-1]
        i += 1

import uuid
import re

from .._compat import iteritems, integer_types
from .regex import REGEX_NOPASSWD, REGEX_UNPACK, REGEX_CONST_STRING, REGEX_W
from .classes import SQLCustomType

PLURALIZE_RULES = [
    (re.compile('child$'), re.compile('child$'), 'children'),
    (re.compile('oot$'), re.compile('oot$'), 'eet'),
    (re.compile('ooth$'), re.compile('ooth$'), 'eeth'),
    (re.compile('l[eo]af$'), re.compile('l([eo])af$'), 'l\\1aves'),
    (re.compile('sis$'), re.compile('sis$'), 'ses'),
    (re.compile('man$'), re.compile('man$'), 'men'),
    (re.compile('ife$'), re.compile('ife$'), 'ives'),
    (re.compile('eau$'), re.compile('eau$'), 'eaux'),
    (re.compile('lf$'), re.compile('lf$'), 'lves'),
    (re.compile('[sxz]$'), re.compile('$'), 'es'),
    (re.compile('[^aeioudgkprt]h$'), re.compile('$'), 'es'),
    (re.compile('(qu|[^aeiou])y$'), re.compile('y$'), 'ies'),
    (re.compile('$'), re.compile('$'), 's'),
    ]

def pluralize(singular, rules=PLURALIZE_RULES):
    for line in rules:
        re_search, re_sub, replace = line
        plural = re_search.search(singular) and re_sub.sub(replace, singular)
        if plural: return plural

def hide_password(uri):
    if isinstance(uri, (list, tuple)):
        return [hide_password(item) for item in uri]
    return REGEX_NOPASSWD.sub('******', uri)

def cleanup(text):
    """
    Validates that the given text is clean: only contains [0-9a-zA-Z_]
    """
    return text

def list_represent(values, row=None):
    return ', '.join(str(v) for v in (values or []))

def xorify(orderby):
    if not orderby:
        return None
    orderby2 = orderby[0]
    for item in orderby[1:]:
        orderby2 = orderby2 | item
    return orderby2

def use_common_filters(query):
    return (query and hasattr(query, 'ignore_common_filters') and \
            not query.ignore_common_filters)

def bar_escape(item):
    return str(item).replace('|', '||')

def bar_encode(items):
    return '|%s|' % '|'.join(bar_escape(item) for item in items if str(item).strip())

def bar_decode_integer(value):
    long = integer_types[-1]
    if not hasattr(value, 'split') and hasattr(value, 'read'):
        value = value.read()
    return [long(x) for x in value.split('|') if x.strip()]

def bar_decode_string(value):
    return [x.replace('||', '|') for x in
            REGEX_UNPACK.split(value[1:-1]) if x.strip()]

def archive_record(qset, fs, archive_table, current_record):
    tablenames = qset.db._adapter.tables(qset.query)
    if len(tablenames) != 1:
        raise RuntimeError("cannot update join")
    for row in qset.select():
        fields = archive_table._filter_fields(row)
        for k, v in iteritems(fs):
            if fields[k] != v:
                fields[current_record] = row.id
                archive_table.insert(**fields)
                break
    return False

def smart_query(fields, text):
    from ..objects import Field, Table
    if not isinstance(fields, (list, tuple)):
        fields = [fields]
    new_fields = []
    for field in fields:
        if isinstance(field, Field):
            new_fields.append(field)
        elif isinstance(field, Table):
            for ofield in field:
                new_fields.append(ofield)
        else:
            raise RuntimeError("fields must be a list of fields")
    fields = new_fields
    field_map = {}
    for field in fields:
        n = field.name.lower()
        if not n in field_map:
            field_map[n] = field
        n = str(field).lower()
        if not n in field_map:
            field_map[n] = field
    constants = {}
    i = 0

    text = re.sub('\s+', ' ', text).lower()
    for a, b in [('&', 'and'),
                 ('|', 'or'),
                 ('~', 'not'),
                 ('==', '='),
                 ('<', '<'),
                 ('>', '>'),
                 ('<=', '<='),
                 ('>=', '>='),
                 ('<>', '!='),
                 ('=<', '<='),
                 ('=>', '>='),
                 ('=', '='),
                 (' less or equal than ', '<='),
                 (' greater or equal than ', '>='),
                 (' equal or less than ', '<='),
                 (' equal or greater than ', '>='),
                 (' less or equal ', '<='),
                 (' greater or equal ', '>='),
                 (' equal or less ', '<='),
                 (' equal or greater ', '>='),
                 (' not equal to ', '!='),
                 (' not equal ', '!='),
                 (' equal to ', '='),
                 (' equal ', '='),
                 (' equals ', '='),
                 (' less than ', '<'),
                 (' greater than ', '>'),
                 (' starts with ', 'startswith'),
                 (' ends with ', 'endswith'),
                 (' not in ', 'notbelongs'),
                 (' in ', 'belongs'),
                 (' is ', '=')]:
        if a[0] == ' ':
            text = text.replace(' is'+a, ' %s ' % b)
        text = text.replace(a, ' %s ' % b)
    text = re.sub('\s+', ' ', text).lower()
    text = re.sub('(?P<a>[\<\>\!\=])\s+(?P<b>[\<\>\!\=])', '\g<a>\g<b>', text)
    query = field = neg = op = logic = None
    for item in text.split():
        if field is None:
            if item == 'not':
                neg = True
            elif not neg and not logic and item in ('and', 'or'):
                logic = item
            elif item in field_map:
                field = field_map[item]
            else:
                raise RuntimeError("Invalid syntax")
        elif not field is None and op is None:
            op = item
        elif not op is None:
            if item.startswith('#'):
                if not item[1:] in constants:
                    raise RuntimeError("Invalid syntax")
                value = constants[item[1:]]
            else:
                value = item
                if field.type in ('text', 'string', 'json'):
                    if op == '=': op = 'like'
            if op == '=': new_query = field == value
            elif op == '<': new_query = field < value
            elif op == '>': new_query = field > value
            elif op == '<=': new_query = field <= value
            elif op == '>=': new_query = field >= value
            elif op == '!=': new_query = field != value
            elif op == 'belongs': new_query = field.belongs(value.split(','))
            elif op == 'notbelongs': new_query = ~field.belongs(value.split(','))
            elif field.type == 'list:string':
                if op == 'contains': new_query = field.contains(value)
                else: raise RuntimeError("Invalid operation")
            elif field.type in ('text', 'string', 'json', 'upload'):
                if op == 'contains': new_query = field.contains(value)
                elif op == 'like': new_query = field.ilike(value)
                elif op == 'startswith': new_query = field.startswith(value)
                elif op == 'endswith': new_query = field.endswith(value)
                else: raise RuntimeError("Invalid operation")
            elif field._db._adapter.dbengine=='google:datastore' and \
                 field.type in ('list:integer', 'list:string', 'list:reference'):
                if op == 'contains': new_query = field.contains(value)
                else: raise RuntimeError("Invalid operation")
            else: raise RuntimeError("Invalid operation")
            if neg: new_query = ~new_query
            if query is None:
                query = new_query
            elif logic == 'and':
                query &= new_query
            elif logic == 'or':
                query |= new_query
            field = op = neg = logic = None
    return query

def auto_validators(field):
    db = field.db
    field_type = field.type
    #: don't apply default validation on custom types
    if isinstance(field_type, SQLCustomType):
        if hasattr(field_type, 'validator'):
            return field_type.validator
        else:
            field_type = field_type.type
    elif not isinstance(field_type, str):
        return []
    #: if a custom method is provided, call it
    if callable(db.validators_method):
        return db.validators_method(field)
    #: apply validators from validators dict if present
    if not db.validators or not isinstance(db.validators, dict):
        return []
    field_validators = db.validators.get(field_type, [])
    if not isinstance(field_validators, (list, tuple)):
        field_validators = [field_validators]
    return field_validators

def _fieldformat(r, id):
    row = r(id)
    if not row:
        return str(id)
    elif hasattr(r, '_format') and isinstance(r._format, str):
        return r._format % row
    elif hasattr(r, '_format') and callable(r._format):
        return r._format(row)
    else:
        return str(id)

class _repr_ref(object):
    def __init__(self, ref=None):
        self.ref = ref

    def __call__(self, value, row=None):
        return value if value is None else _fieldformat(self.ref, value)

class _repr_ref_list(_repr_ref):
    def __call__(self, value, row=None):
        if not value:
            return None
        refs = None
        db, id = self.ref._db, self.ref._id
        if db._adapter.dbengine == 'google:datastore':
            def count(values):
                return db(id.belongs(values)).select(id)
            rx = range(0, len(value), 30)
            refs = reduce(lambda a, b: a & b, [count(value[i:i+30])
                          for i in rx])
        else:
            refs = db(id.belongs(value)).select(id)
        return refs and ', '.join(
            _fieldformat(self.ref, x) for x in value) or ''

def auto_represent(field):
    if field.represent:
        return field.represent
    if field.db and field.type.startswith('reference') and \
            field.type.find('.') < 0 and field.type[10:] in field.db.tables:
        referenced = field.db[field.type[10:]]
        return _repr_ref(referenced)
    elif field.db and field.type.startswith('list:reference') and \
            field.type.find('.') < 0 and field.type[15:] in field.db.tables:
        referenced = field.db[field.type[15:]]
        return _repr_ref_list(referenced)
    return field.represent

def varquote_aux(name, quotestr='%s'):
    return name if REGEX_W.match(name) else quotestr % name

def uuid2int(uuidv):
    return uuid.UUID(uuidv).int

def int2uuid(n):
    return str(uuid.UUID(int=n))

# Geodal utils
def geoPoint(x, y):
    return "POINT (%f %f)" % (x, y)

def geoLine(*line):
    return "LINESTRING (%s)" % ','.join("%f %f" % item for item in line)

def geoPolygon(*line):
    return "POLYGON ((%s))" % ','.join("%f %f" % item for item in line)


        options = self.parse_options_string(options_string)
        self.reset_task_messages()
        call_task("pavelib.js_test.test_js_run", options=options)
        self.verify_messages(options=options, dev_mode=False)

"""Unit tests for the Paver JavaScript testing tasks."""

import ddt
from mock import patch
from paver.easy import call_task

import pavelib.js_test
from pavelib.utils.envs import Env

from .utils import PaverTestCase

@ddt.ddt
class TestPaverJavaScriptTestTasks(PaverTestCase):
    """
    Test the Paver JavaScript testing tasks.
    """

    EXPECTED_DELETE_JAVASCRIPT_REPORT_COMMAND = u'find {platform_root}/reports/javascript -type f -delete'
    EXPECTED_INSTALL_NPM_ASSETS_COMMAND = u'install npm_assets'
    EXPECTED_KARMA_OPTIONS = (
        u"{config_file} "
        u"--single-run={single_run} "
        u"--capture-timeout=60000 "
        u"--junitreportpath="
        u"{platform_root}/reports/javascript/javascript_xunit-{suite}.xml "
        u"--browsers={browser}"
    )
    EXPECTED_COVERAGE_OPTIONS = (
        u' --coverage --coveragereportpath={platform_root}/reports/javascript/coverage-{suite}.xml'
    )

    EXPECTED_COMMANDS = [
        u"make report_dir",
        u'git clean -fqdx test_root/logs test_root/data test_root/staticfiles test_root/uploads',
        u"find . -name '.git' -prune -o -name '*.pyc' -exec rm {} \\;",
        u'rm -rf test_root/log/auto_screenshots/*',
        u"rm -rf /tmp/mako_[cl]ms",
    ]

    def setUp(self):
        super(TestPaverJavaScriptTestTasks, self).setUp()

        # Mock the paver @needs decorator
        self._mock_paver_needs = patch.object(pavelib.js_test.test_js, 'needs').start()
        self._mock_paver_needs.return_value = 0

        # Cleanup mocks
        self.addCleanup(self._mock_paver_needs.stop)

    @ddt.data(
        [""],
        ["--coverage"],
        ["--suite=lms"],
        ["--suite=lms --coverage"],
    )
    @ddt.unpack
    def test_test_js_run(self, options_string):
        """
        Test the "test_js_run" task.
        """

    @ddt.data(
        [""],
        ["--port=9999"],
        ["--suite=lms"],
        ["--suite=lms --port=9999"],
    )
    @ddt.unpack
    def test_test_js_dev(self, options_string):
        """
        Test the "test_js_run" task.
        """
        options = self.parse_options_string(options_string)
        self.reset_task_messages()
        call_task("pavelib.js_test.test_js_dev", options=options)
        self.verify_messages(options=options, dev_mode=True)

    def parse_options_string(self, options_string):
        """
        Parse a string containing the options for a test run
        """
        parameters = options_string.split(" ")
        suite = "all"
        if "--system=lms" in parameters:
            suite = "lms"
        elif "--system=common" in parameters:
            suite = "common"
        coverage = "--coverage" in parameters
        port = None
        if "--port=9999" in parameters:
            port = 9999
        return {
            "suite": suite,
            "coverage": coverage,
            "port": port,
        }

    def verify_messages(self, options, dev_mode):
        """
        Verify that the messages generated when running tests are as expected
        for the specified options and dev_mode.
        """
        is_coverage = options['coverage']
        port = options['port']
        expected_messages = []
        suites = Env.JS_TEST_ID_KEYS if options['suite'] == 'all' else [options['suite']]

        expected_messages.extend(self.EXPECTED_COMMANDS)
        if not dev_mode and not is_coverage:
            expected_messages.append(self.EXPECTED_DELETE_JAVASCRIPT_REPORT_COMMAND.format(
                platform_root=self.platform_root
            ))
        expected_messages.append(self.EXPECTED_INSTALL_NPM_ASSETS_COMMAND)

        command_template = (
            u'nodejs --max_old_space_size=4096 node_modules/.bin/karma start {options}'
        )

        for suite in suites:
            # Karma test command
            if suite != 'jest-snapshot':
                karma_config_file = Env.KARMA_CONFIG_FILES[Env.JS_TEST_ID_KEYS.index(suite)]
                expected_test_tool_command = command_template.format(
                    options=self.EXPECTED_KARMA_OPTIONS.format(
                        config_file=karma_config_file,
                        single_run='false' if dev_mode else 'true',
                        suite=suite,
                        platform_root=self.platform_root,
                        browser=Env.KARMA_BROWSER,
                    ),
                )
                if is_coverage:
                    expected_test_tool_command += self.EXPECTED_COVERAGE_OPTIONS.format(
                        platform_root=self.platform_root,
                        suite=suite
                    )
                if port:
                    expected_test_tool_command += u" --port={port}".format(port=port)
            else:
                expected_test_tool_command = u'jest'

            expected_messages.append(expected_test_tool_command)

        self.assertEqual(self.task_messages, expected_messages)


        print('\n','Device','Name','Port','Node','Name')
        for d in range(len(self)):
            print(repr(d+1).rjust(6), end=' ')
            self[d].Print(1)

"""
SystemDescription.py
"""
from __future__ import print_function
from __future__ import absolute_import

# All rights reserved worldwide.
# This file is part of SignalIntegrity.
from SignalIntegrity.Lib.Devices import Tee
from SignalIntegrity.Lib.Devices import Thru
from .Device import Device
from .UniqueNameFactory import UniqueNameFactory
from SignalIntegrity.Lib.Exception import SignalIntegrityExceptionSystemDescription

class SystemDescription(list):
    """Allows the construction of system descriptions for use with all of the
    classes that solve schematics and netlists

    Often, this class will be used to construct the system description and
    then passed to another class for problem solution

    A system description is fundamentally a list of devices, which in turn are lists
    of ports and port connections."""
    def __init__(self,sd=None):
        """Constructor
        @param sd (optional, defaults to None) instance of class SystemDescription
        Initializes a system description
        """
        if not sd is None:
            list.__init__(self,list(sd))
            self.m_UniqueDevice=sd.m_UniqueDevice
            self.m_UniqueNode=sd.m_UniqueNode
        else:
            list.__init__(self,[])
            self.m_UniqueDevice=UniqueNameFactory('#')
            self.m_UniqueNode=UniqueNameFactory('n')
    def AddDevice(self,Name,Ports,SParams=None,Type='device'):
        """Adds a device to the system
        @param Name string name of device to add
        @param Ports integer number of ports in the device
        @param SParams (optional) s-parameter matrix for device
        @param Type type of device defaults to 'device'
        Adds a device to the system with the given name, s-parameters and number of ports
        The type is always 'device' and should not be overridden except for one case where the device
        being added is an 'unknown' to be solved for."""
        # pragma: silent exclude
        if Name in self.DeviceNames():
            raise SignalIntegrityExceptionSystemDescription(
                'duplicate device name: '+str(Name))
        self.append(Device(Name,Ports,Type))
        if isinstance(SParams,list):
            self.AssignSParameters(Name,SParams)
    def AssignM(self,DeviceN,DeviceP,MName):
        """Assigns a stimulus to a device port
        @param DeviceN string name of device
        @param DeviceP integer port number of device
        @param MName string name of a stimulus
        Assigns a stimulus in name only as emanating from the device port specified
        """
        di = self.IndexOfDevice(DeviceN)
        self[di][DeviceP-1].M = MName
    def DeviceNames(self):
        """Returns a list of device names in the system
        @return a list of the names of all of the devices in the system
        """
        return [self[d].Name for d in range(len(self))]
    def IndexOfDevice(self,DeviceName):
        """Returns the index of a named device in the system
        @param DeviceName string name of a device
        @return integer index of the named device
        @throw SignalIntegrityExceptionSystemDescription if device not found
        """
        # pragma: silent exclude
        try:
        # pragma: include outdent
            return self.DeviceNames().index(DeviceName)
        # pragma: silent exclude indent
        except ValueError:
            raise SignalIntegrityExceptionSystemDescription(
                'no device named: '+str(DeviceName))
    def _InsertNodeName(self,DeviceName,Port,AName,BName):
        di = self.IndexOfDevice(DeviceName)
        self[di][Port-1].A = AName
        self[di][Port-1].B = BName
    def CheckConnections(self):
        """Checks the validity of the connections in the system
        @throw SignalIntegrityExceptionSystemDescription if there are no devices
        @throw SignalIntegrityExceptionSystemDescription if any of the devices have unconnected device ports
        """
        if len(self)==0:
            raise SignalIntegrityExceptionSystemDescription('no devices')
        if not all([self[d][p].IsConnected()
            for d in range(len(self)) for p in range(len(self[d]))]):
            raise SignalIntegrityExceptionSystemDescription('unconnected device ports')
    def ConnectDevicePort(self,FromN,FromP,ToN,ToP):
        """Connects one device port to another
        @param FromN string name of from device
        @param FromP integer port number of from device
        @param ToN string name of to device
        @param ToP integer port number of to device
        Makes a connection from one device port to another.

        It's okay if devices are already connected and multiple connections are
        allowed and are handled properly.
        """
        # pragma: silent exclude
        try:
        # pragma: include outdent
            dfi = self.IndexOfDevice(FromN)
            dti = self.IndexOfDevice(ToN)
            if not self[dfi][FromP-1].IsConnected():
                if not self[dti][ToP-1].IsConnected():
                    uN1,uN2 = (self.m_UniqueNode.Name(),self.m_UniqueNode.Name())
                    self._InsertNodeName(FromN,FromP,uN2,uN1)
                    self._InsertNodeName(ToN,ToP,uN1,uN2)
                else:
                    self.ConnectDevicePort(ToN,ToP,FromN,FromP)
            else:
                TeeN = self.m_UniqueDevice.Name()
                self.AddDevice(TeeN,3)
                self.AssignSParameters(TeeN,Tee())
                self._InsertNodeName(TeeN,1,self[dfi][FromP-1].A,self[dfi][FromP-1].B)
                self._InsertNodeName(FromN,FromP,'','')
                self.ConnectDevicePort(FromN,FromP,TeeN,2)
                self.ConnectDevicePort(TeeN,3,ToN,ToP)
        # pragma: silent exclude indent
        except IndexError:
            raise SignalIntegrityExceptionSystemDescription(
                'cannot connect device ports '+str(FromN)+' '+str(FromP)+' to '+
                str(ToN)+' '+str(ToP))
    def AddPort(self,DeviceName,DevicePort,SystemPort,AddThru=False):
        """Adds a system port at a specified device port
        @param DeviceName string name of device
        @param DevicePort integer port number of device
        @param SystemPort integer port number
        @param AddThru boolean whether to force a thru between the system port and the device port.
        Adds a system port to a device port for the solutions of s-parameters or for deembedding.

        In the theory, sometimes it's necessary to add a thru between a system port and a device port.
        But it turns out that this is only necessary when connecting a system port directly to a port
        of an unknown device in a deembedding problem.  Although the ability to force the addition of
        a thru is retained, the code actually checks for this situation and adds a thru automatically
        so currently, there are no situations known where AddThru needs to be set True.

        @todo Consider removing the AddThru argument
        """
        PortName = 'P'+str(SystemPort)
        self.AddDevice(PortName,1,[[0.0]])
        self.AssignM(PortName,1,'m'+str(SystemPort))
        if not AddThru:
            AddThru = self[self.IndexOfDevice(DeviceName)].Type == 'unknown'
        if AddThru:
            thruName=self.m_UniqueDevice.Name()
            self.AddDevice(thruName,2,Thru())
            self.ConnectDevicePort(PortName,1,thruName,1)
            self.ConnectDevicePort(thruName,2,DeviceName,DevicePort)
        else:
            self.ConnectDevicePort(PortName,1,DeviceName,DevicePort)
    def AssignSParameters(self,DeviceName,SParameters):
        """Assigns s-parameters to a device
        @param DeviceName string name of a device in the system
        @param SParameters an s-parameter matrix
        """
        self[self.IndexOfDevice(DeviceName)].AssignSParameters(SParameters)
    def Print(self):
        """Prints out an ASCII description of the system"""


        check_is_fitted(self, 'mean_')

        X = check_array(X)
        Xr = X - self.mean_
        n_features = X.shape[1]
        precision = self.get_precision()
        log_like = -.5 * (Xr * (np.dot(Xr, precision))).sum(axis=1)
        log_like -= .5 * (n_features * log(2. * np.pi) -
                          fast_logdet(precision))
        return log_like

""" Principal Component Analysis
"""

# Author: Alexandre Gramfort <example@nnthink.com>
#         Olivier Grisel <example@nnthink.com>
#         Mathieu Blondel <example@nnthink.com>
#         Denis A. Engemann <example@nnthink.com>
#         Michael Eickenberg <example@nnthink.com>
#         Giorgio Patrini <example@nnthink.com>

from math import log, sqrt
import numbers

import numpy as np
from scipy import linalg
from scipy.special import gammaln
from scipy.sparse import issparse
from scipy.sparse.linalg import svds

from ..externals import six

from .base import _BasePCA
from ..utils import check_random_state
from ..utils import check_array
from ..utils.extmath import fast_logdet, randomized_svd, svd_flip
from ..utils.extmath import stable_cumsum
from ..utils.validation import check_is_fitted

def _assess_dimension_(spectrum, rank, n_samples, n_features):
    """Compute the likelihood of a rank ``rank`` dataset

    The dataset is assumed to be embedded in gaussian noise of shape(n,
    dimf) having spectrum ``spectrum``.

    Parameters
    ----------
    spectrum : array of shape (n)
        Data spectrum.
    rank : int
        Tested rank value.
    n_samples : int
        Number of samples.
    n_features : int
        Number of features.

    Returns
    -------
    ll : float,
        The log-likelihood

    Notes
    -----
    This implements the method of `Thomas P. Minka:
    Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604`
    """
    if rank > len(spectrum):
        raise ValueError("The tested rank cannot exceed the rank of the"
                         " dataset")

    pu = -rank * log(2.)
    for i in range(rank):
        pu += (gammaln((n_features - i) / 2.) -
               log(np.pi) * (n_features - i) / 2.)

    pl = np.sum(np.log(spectrum[:rank]))
    pl = -pl * n_samples / 2.

    if rank == n_features:
        pv = 0
        v = 1
    else:
        v = np.sum(spectrum[rank:]) / (n_features - rank)
        pv = -np.log(v) * n_samples * (n_features - rank) / 2.

    m = n_features * rank - rank * (rank + 1.) / 2.
    pp = log(2. * np.pi) * (m + rank + 1.) / 2.

    pa = 0.
    spectrum_ = spectrum.copy()
    spectrum_[rank:n_features] = v
    for i in range(rank):
        for j in range(i + 1, len(spectrum)):
            pa += log((spectrum[i] - spectrum[j]) *
                      (1. / spectrum_[j] - 1. / spectrum_[i])) + log(n_samples)

    ll = pu + pl + pv + pp - pa / 2. - rank * log(n_samples) / 2.

    return ll

def _infer_dimension_(spectrum, n_samples, n_features):
    """Infers the dimension of a dataset of shape (n_samples, n_features)

    The dataset is described by its spectrum `spectrum`.
    """
    n_spectrum = len(spectrum)
    ll = np.empty(n_spectrum)
    for rank in range(n_spectrum):
        ll[rank] = _assess_dimension_(spectrum, rank, n_samples, n_features)
    return ll.argmax()

class PCA(_BasePCA):
    """Principal component analysis (PCA)

    Linear dimensionality reduction using Singular Value Decomposition of the
    data to project it to a lower dimensional space.

    It uses the LAPACK implementation of the full SVD or a randomized truncated
    SVD by the method of Halko et al. 2009, depending on the shape of the input
    data and the number of components to extract.

    It can also use the scipy.sparse.linalg ARPACK implementation of the
    truncated SVD.

    Notice that this class does not support sparse input. See
    :class:`TruncatedSVD` for an alternative with sparse data.

    Read more in the :ref:`User Guide <PCA>`.

    Parameters
    ----------
    n_components : int, float, None or string
        Number of components to keep.
        if n_components is not set all components are kept::

            n_components == min(n_samples, n_features)

        If ``n_components == 'mle'`` and ``svd_solver == 'full'``, Minka's
        MLE is used to guess the dimension. Use of ``n_components == 'mle'``
        will interpret ``svd_solver == 'auto'`` as ``svd_solver == 'full'``.

        If ``0 < n_components < 1`` and ``svd_solver == 'full'``, select the
        number of components such that the amount of variance that needs to be
        explained is greater than the percentage specified by n_components.

        If ``svd_solver == 'arpack'``, the number of components must be
        strictly less than the minimum of n_features and n_samples.

        Hence, the None case results in::

            n_components == min(n_samples, n_features) - 1

    copy : bool (default True)
        If False, data passed to fit are overwritten and running
        fit(X).transform(X) will not yield the expected results,
        use fit_transform(X) instead.

    whiten : bool, optional (default False)
        When True (False by default) the `components_` vectors are multiplied
        by the square root of n_samples and then divided by the singular values
        to ensure uncorrelated outputs with unit component-wise variances.

        Whitening will remove some information from the transformed signal
        (the relative variance scales of the components) but can sometime
        improve the predictive accuracy of the downstream estimators by
        making their data respect some hard-wired assumptions.

    svd_solver : string {'auto', 'full', 'arpack', 'randomized'}
        auto :
            the solver is selected by a default policy based on `X.shape` and
            `n_components`: if the input data is larger than 500x500 and the
            number of components to extract is lower than 80% of the smallest
            dimension of the data, then the more efficient 'randomized'
            method is enabled. Otherwise the exact full SVD is computed and
            optionally truncated afterwards.
        full :
            run exact full SVD calling the standard LAPACK solver via
            `scipy.linalg.svd` and select the components by postprocessing
        arpack :
            run SVD truncated to n_components calling ARPACK solver via
            `scipy.sparse.linalg.svds`. It requires strictly
            0 < n_components < min(X.shape)
        randomized :
            run randomized SVD by the method of Halko et al.

        .. versionadded:: 0.18.0

    tol : float >= 0, optional (default .0)
        Tolerance for singular values computed by svd_solver == 'arpack'.

        .. versionadded:: 0.18.0

    iterated_power : int >= 0, or 'auto', (default 'auto')
        Number of iterations for the power method computed by
        svd_solver == 'randomized'.

        .. versionadded:: 0.18.0

    random_state : int, RandomState instance or None, optional (default None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`. Used when ``svd_solver`` == 'arpack' or 'randomized'.

        .. versionadded:: 0.18.0

    Attributes
    ----------
    components_ : array, shape (n_components, n_features)
        Principal axes in feature space, representing the directions of
        maximum variance in the data. The components are sorted by
        ``explained_variance_``.

    explained_variance_ : array, shape (n_components,)
        The amount of variance explained by each of the selected components.

        Equal to n_components largest eigenvalues
        of the covariance matrix of X.

        .. versionadded:: 0.18

    explained_variance_ratio_ : array, shape (n_components,)
        Percentage of variance explained by each of the selected components.

        If ``n_components`` is not set then all components are stored and the
        sum of the ratios is equal to 1.0.

    singular_values_ : array, shape (n_components,)
        The singular values corresponding to each of the selected components.
        The singular values are equal to the 2-norms of the ``n_components``
        variables in the lower-dimensional space.

    mean_ : array, shape (n_features,)
        Per-feature empirical mean, estimated from the training set.

        Equal to `X.mean(axis=0)`.

    n_components_ : int
        The estimated number of components. When n_components is set
        to 'mle' or a number between 0 and 1 (with svd_solver == 'full') this
        number is estimated from input data. Otherwise it equals the parameter
        n_components, or the lesser value of n_features and n_samples
        if n_components is None.

    noise_variance_ : float
        The estimated noise covariance following the Probabilistic PCA model
        from Tipping and Bishop 1999. See "Pattern Recognition and
        Machine Learning" by C. Bishop, 12.2.1 p. 574 or
        http://example.com. It is required to
        compute the estimated data covariance and score samples.

        Equal to the average of (min(n_features, n_samples) - n_components)
        smallest eigenvalues of the covariance matrix of X.

    References
    ----------
    For n_components == 'mle', this class uses the method of `Minka, T. P.
    "Automatic choice of dimensionality for PCA". In NIPS, pp. 598-604`

    Implements the probabilistic PCA model from:
    `Tipping, M. E., and Bishop, C. M. (1999). "Probabilistic principal
    component analysis". Journal of the Royal Statistical Society:
    Series B (Statistical Methodology), 61(3), 611-622.
    via the score and score_samples methods.
    See http://www.miketipping.com/papers/met-mppca.pdf

    For svd_solver == 'arpack', refer to `scipy.sparse.linalg.svds`.

    For svd_solver == 'randomized', see:
    `Halko, N., Martinsson, P. G., and Tropp, J. A. (2011).
    "Finding structure with randomness: Probabilistic algorithms for
    constructing approximate matrix decompositions".
    SIAM review, 53(2), 217-288.` and also
    `Martinsson, P. G., Rokhlin, V., and Tygert, M. (2011).
    "A randomized algorithm for the decomposition of matrices".
    Applied and Computational Harmonic Analysis, 30(1), 47-68.`

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.decomposition import PCA
    >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
    >>> pca = PCA(n_components=2)
    >>> pca.fit(X)
    PCA(copy=True, iterated_power='auto', n_components=2, random_state=None,
      svd_solver='auto', tol=0.0, whiten=False)
    >>> print(pca.explained_variance_ratio_)  # doctest: +ELLIPSIS
    [0.9924... 0.0075...]
    >>> print(pca.singular_values_)  # doctest: +ELLIPSIS
    [6.30061... 0.54980...]

    >>> pca = PCA(n_components=2, svd_solver='full')
    >>> pca.fit(X)                 # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
    PCA(copy=True, iterated_power='auto', n_components=2, random_state=None,
      svd_solver='full', tol=0.0, whiten=False)
    >>> print(pca.explained_variance_ratio_)  # doctest: +ELLIPSIS
    [0.9924... 0.00755...]
    >>> print(pca.singular_values_)  # doctest: +ELLIPSIS
    [6.30061... 0.54980...]

    >>> pca = PCA(n_components=1, svd_solver='arpack')
    >>> pca.fit(X)
    PCA(copy=True, iterated_power='auto', n_components=1, random_state=None,
      svd_solver='arpack', tol=0.0, whiten=False)
    >>> print(pca.explained_variance_ratio_)  # doctest: +ELLIPSIS
    [0.99244...]
    >>> print(pca.singular_values_)  # doctest: +ELLIPSIS
    [6.30061...]

    See also
    --------
    KernelPCA
    SparsePCA
    TruncatedSVD
    IncrementalPCA
    """

    def __init__(self, n_components=None, copy=True, whiten=False,
                 svd_solver='auto', tol=0.0, iterated_power='auto',
                 random_state=None):
        self.n_components = n_components
        self.copy = copy
        self.whiten = whiten
        self.svd_solver = svd_solver
        self.tol = tol
        self.iterated_power = iterated_power
        self.random_state = random_state

    def fit(self, X, y=None):
        """Fit the model with X.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training data, where n_samples is the number of samples
            and n_features is the number of features.

        y : Ignored

        Returns
        -------
        self : object
            Returns the instance itself.
        """
        self._fit(X)
        return self

    def fit_transform(self, X, y=None):
        """Fit the model with X and apply the dimensionality reduction on X.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training data, where n_samples is the number of samples
            and n_features is the number of features.

        y : Ignored

        Returns
        -------
        X_new : array-like, shape (n_samples, n_components)

        """
        U, S, V = self._fit(X)
        U = U[:, :self.n_components_]

        if self.whiten:
            U *= sqrt(X.shape[0] - 1)
        else:
            # X_new = X * V = U * S * V^T * V = U * S
            U *= S[:self.n_components_]

        return U

    def _fit(self, X):
        """Dispatch to the right submethod depending on the chosen solver."""

        # Raise an error for sparse input.
        # This is more informative than the generic one raised by check_array.
        if issparse(X):
            raise TypeError('PCA does not support sparse input. See '
                            'TruncatedSVD for a possible alternative.')

        X = check_array(X, dtype=[np.float64, np.float32], ensure_2d=True,
                        copy=self.copy)

        if self.n_components is None:
            if self.svd_solver != 'arpack':
                n_components = min(X.shape)
            else:
                n_components = min(X.shape) - 1
        else:
            n_components = self.n_components

        # Handle svd_solver
        self._fit_svd_solver = self.svd_solver
        if self._fit_svd_solver == 'auto':
            # Small problem or n_components == 'mle', just call full PCA
            if max(X.shape) <= 500 or n_components == 'mle':
                self._fit_svd_solver = 'full'
            elif n_components >= 1 and n_components < .8 * min(X.shape):
                self._fit_svd_solver = 'randomized'
            # This is also the case of n_components in (0,1)
            else:
                self._fit_svd_solver = 'full'

        # Call different fits for either full or truncated SVD
        if self._fit_svd_solver == 'full':
            return self._fit_full(X, n_components)
        elif self._fit_svd_solver in ['arpack', 'randomized']:
            return self._fit_truncated(X, n_components, self._fit_svd_solver)
        else:
            raise ValueError("Unrecognized svd_solver='{0}'"
                             "".format(self._fit_svd_solver))

    def _fit_full(self, X, n_components):
        """Fit the model by computing full SVD on X"""
        n_samples, n_features = X.shape

        if n_components == 'mle':
            if n_samples < n_features:
                raise ValueError("n_components='mle' is only supported "
                                 "if n_samples >= n_features")
        elif not 0 <= n_components <= min(n_samples, n_features):
            raise ValueError("n_components=%r must be between 0 and "
                             "min(n_samples, n_features)=%r with "
                             "svd_solver='full'"
                             % (n_components, min(n_samples, n_features)))
        elif n_components >= 1:
            if not isinstance(n_components, (numbers.Integral, np.integer)):
                raise ValueError("n_components=%r must be of type int "
                                 "when greater than or equal to 1, "
                                 "was of type=%r"
                                 % (n_components, type(n_components)))

        # Center data
        self.mean_ = np.mean(X, axis=0)
        X -= self.mean_

        U, S, V = linalg.svd(X, full_matrices=False)
        # flip eigenvectors' sign to enforce deterministic output
        U, V = svd_flip(U, V)

        components_ = V

        # Get variance explained by singular values
        explained_variance_ = (S ** 2) / (n_samples - 1)
        total_var = explained_variance_.sum()
        explained_variance_ratio_ = explained_variance_ / total_var
        singular_values_ = S.copy()  # Store the singular values.

        # Postprocess the number of components required
        if n_components == 'mle':
            n_components = \
                _infer_dimension_(explained_variance_, n_samples, n_features)
        elif 0 < n_components < 1.0:
            # number of components for which the cumulated explained
            # variance percentage is superior to the desired threshold
            ratio_cumsum = stable_cumsum(explained_variance_ratio_)
            n_components = np.searchsorted(ratio_cumsum, n_components) + 1

        # Compute noise covariance using Probabilistic PCA model
        # The sigma2 maximum likelihood (cf. eq. 12.46)
        if n_components < min(n_features, n_samples):
            self.noise_variance_ = explained_variance_[n_components:].mean()
        else:
            self.noise_variance_ = 0.

        self.n_samples_, self.n_features_ = n_samples, n_features
        self.components_ = components_[:n_components]
        self.n_components_ = n_components
        self.explained_variance_ = explained_variance_[:n_components]
        self.explained_variance_ratio_ = \
            explained_variance_ratio_[:n_components]
        self.singular_values_ = singular_values_[:n_components]

        return U, S, V

    def _fit_truncated(self, X, n_components, svd_solver):
        """Fit the model by computing truncated SVD (by ARPACK or randomized)
        on X
        """
        n_samples, n_features = X.shape

        if isinstance(n_components, six.string_types):
            raise ValueError("n_components=%r cannot be a string "
                             "with svd_solver='%s'"
                             % (n_components, svd_solver))
        elif not 1 <= n_components <= min(n_samples, n_features):
            raise ValueError("n_components=%r must be between 1 and "
                             "min(n_samples, n_features)=%r with "
                             "svd_solver='%s'"
                             % (n_components, min(n_samples, n_features),
                                svd_solver))
        elif not isinstance(n_components, (numbers.Integral, np.integer)):
            raise ValueError("n_components=%r must be of type int "
                             "when greater than or equal to 1, was of type=%r"
                             % (n_components, type(n_components)))
        elif svd_solver == 'arpack' and n_components == min(n_samples,
                                                            n_features):
            raise ValueError("n_components=%r must be strictly less than "
                             "min(n_samples, n_features)=%r with "
                             "svd_solver='%s'"
                             % (n_components, min(n_samples, n_features),
                                svd_solver))

        random_state = check_random_state(self.random_state)

        # Center data
        self.mean_ = np.mean(X, axis=0)
        X -= self.mean_

        if svd_solver == 'arpack':
            # random init solution, as ARPACK does it internally
            v0 = random_state.uniform(-1, 1, size=min(X.shape))
            U, S, V = svds(X, k=n_components, tol=self.tol, v0=v0)
            # svds doesn't abide by scipy.linalg.svd/randomized_svd
            # conventions, so reverse its outputs.
            S = S[::-1]
            # flip eigenvectors' sign to enforce deterministic output
            U, V = svd_flip(U[:, ::-1], V[::-1])

        elif svd_solver == 'randomized':
            # sign flipping is done inside
            U, S, V = randomized_svd(X, n_components=n_components,
                                     n_iter=self.iterated_power,
                                     flip_sign=True,
                                     random_state=random_state)

        self.n_samples_, self.n_features_ = n_samples, n_features
        self.components_ = V
        self.n_components_ = n_components

        # Get variance explained by singular values
        self.explained_variance_ = (S ** 2) / (n_samples - 1)
        total_var = np.var(X, ddof=1, axis=0)
        self.explained_variance_ratio_ = \
            self.explained_variance_ / total_var.sum()
        self.singular_values_ = S.copy()  # Store the singular values.

        if self.n_components_ < min(n_features, n_samples):
            self.noise_variance_ = (total_var.sum() -
                                    self.explained_variance_.sum())
            self.noise_variance_ /= min(n_features, n_samples) - n_components
        else:
            self.noise_variance_ = 0.

        return U, S, V

    def score_samples(self, X):
        """Return the log-likelihood of each sample.

        See. "Pattern Recognition and Machine Learning"
        by C. Bishop, 12.2.1 p. 574
        or http://www.miketipping.com/papers/met-mppca.pdf

        Parameters
        ----------
        X : array, shape(n_samples, n_features)
            The data.

        Returns
        -------
        ll : array, shape (n_samples,)
            Log-likelihood of each sample under the current model
        """

    def score(self, X, y=None):
        """Return the average log-likelihood of all samples.

        See. "Pattern Recognition and Machine Learning"
        by C. Bishop, 12.2.1 p. 574
        or http://www.miketipping.com/papers/met-mppca.pdf

        Parameters
        ----------
        X : array, shape(n_samples, n_features)
            The data.

        y : Ignored

        Returns
        -------
        ll : float
            Average log-likelihood of the samples under the current model
        """
        return np.mean(self.score_samples(X))


class StructuralConnectionApplyTo(Enum,IComparable,IFormattable,IConvertible):
 """
 An enumerated type that represents the type of structural locations to which a connection annotation may be applied.

 enum StructuralConnectionApplyTo,values: BeamsAndBraces (0),ColumnBase (2),ColumnTop (1),Connection (3)
 """
 def __eq__(self,*args):
  """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """

 def __format__(self,*args):
  """ __format__(formattable: IFormattable,format: str) -> str """
  pass
 def __ge__(self,*args):
  pass
 def __gt__(self,*args):
  pass
 def __init__(self,*args):
  """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
  pass
 def __le__(self,*args):
  pass
 def __lt__(self,*args):
  pass
 def __ne__(self,*args):
  pass
 def __reduce_ex__(self,*args):
  pass
 def __str__(self,*args):
  pass
 BeamsAndBraces=None
 ColumnBase=None
 ColumnTop=None
 Connection=None
 value__=None


        if exctype is error.DiagnosticError and not _should_print_backtrace():
            # TODO(@jroesch): consider moving to C++?
            print("note: run with `TVM_BACKTRACE=1` environment variable to display a backtrace.")
        else:
            exception_hook(exctype, value, trbk)

        if hasattr(multiprocessing, "active_children"):
            for p in multiprocessing.active_children():
                p.terminate()

"""TVM: Open Deep Learning Compiler Stack."""
import multiprocessing
import sys
import os
import traceback

# top-level alias
# tvm._ffi
from ._ffi.base import TVMError, __version__
from ._ffi.runtime_ctypes import DataTypeCode, DataType
from ._ffi import register_object, register_func, register_extension, get_global_func

# top-level alias
# tvm.runtime
from .runtime.object import Object
from .runtime.ndarray import context, cpu, gpu, opencl, cl, vulkan, metal, mtl
from .runtime.ndarray import vpi, rocm, ext_dev, micro_dev, hexagon
from .runtime import ndarray as nd

# tvm.error
from . import error

# tvm.ir
from .ir import IRModule
from .ir import transform
from .ir import container
from . import ir

# tvm.tir
from . import tir

# tvm.target
from . import target

# tvm.te
from . import te

# tvm.driver
from .driver import build, lower

# tvm.parser
from . import parser

# others
from . import arith

# support infra
from . import support

# Contrib initializers
from .contrib import rocm as _rocm, nvcc as _nvcc, sdaccel as _sdaccel

# NOTE: This file should be python2 compatible so we can
# raise proper error message when user run the package using
# an older version of the python

def _should_print_backtrace():
    in_pytest = "PYTEST_CURRENT_TEST" in os.environ
    tvm_backtrace = os.environ.get("TVM_BACKTRACE", "0")

    try:
        tvm_backtrace = bool(int(tvm_backtrace))
    except ValueError:
        raise ValueError(
            "invalid value for TVM_BACKTRACE {}, please set to 0 or 1.".format(tvm_backtrace)
        )

    return in_pytest or tvm_backtrace

def tvm_wrap_excepthook(exception_hook):
    """Wrap given excepthook with TVM additional work."""

    def wrapper(exctype, value, trbk):
        """Clean subprocesses when TVM is interrupted."""

    return wrapper

sys.excepthook = tvm_wrap_excepthook(sys.excepthook)